Search code examples
phpfor-loopnested-loops

A funny exercise using by for loop


I am interested in the loop exercise and saw a funny questions as below shown.

  • Create a script to construct the following pattern, using a nested for loop.
  • For the implementation, please using "echo" and showed by the table form.
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 1 1 1 0
0 0 1 0 0

I try hard and coding an hour but I could not be succes and I can implement an triangle as

1 0 0 0 0
1 1 0 0 0
1 1 1 0 0
1 1 1 1 0
1 1 1 1 1

I understand my knowledge of martix and array is poor, I am pleased if anyone can teach me, thank you.

code of triangle loop:

    <?php 
        for($i=1;$i<=5;$i++){  
            for ($j=1;$j<=$i;$j++){  
                echo "1";  
            } 
            echo "</br>";  
        }
    ?>

Hello everyone, I had been completed the execrise by stupid way, thanks for everyone who helps me.

Here is my silly code:

for($i=1;$i<=$num;$i++){
  for($j=1;$j<=$num;$j++){  
    if($i==3||$j==3){  
      echo ' 1 ';
    }
    else if($i==$j-2){
      echo ' 1 ';
    }
    else if($j==$i-2){
      echo ' 1 ';
    }
    else if($i==2&&$j==2||$i==4&&$j==4){
      echo ' 1 ';
    }
    else{
      echo ' 0 ';
    }                 
  }   
    echo'<br>';   
}

Solution

  • Here's an option using str_pad() to pad the left and right side of the "ones" evenly. I'm using implode() and array_fill() to create a string of ones that is the correct length to start with.

    $size = 5;
    // expanding
    for($width = 1; $width <= $size; $width += 2) { // rows
        $ones = implode(array_fill(0, $width, '1'));
        echo str_pad($ones, $size, '0', STR_PAD_BOTH) . PHP_EOL;
    }    
    
    // contracting (exclude the first row where it's all ones
    for($width = $size - 2; $width >= 1; $width -= 2) { // rows
        $ones = implode(array_fill(0, $width, '1'));
        echo str_pad($ones, $size, '0', STR_PAD_BOTH) . PHP_EOL;
    }
    

    For kicks, here's another example that only uses one loop.


    Note: your specs say to use nested for loops - CommuSoft's answer fits that description nicely using math logic.