Search code examples
phpfor-looplogicmodulotriangle

Print triangular number patterns with loops and modulus calculation


I need to print a number pattern like this:

1
12
123
1234
2
23
234
2341
3
34
341
3412
4
41
412
4123

My code:

for($i=1; $i<=4; ++$i) {
    for($j=1; $j<=$i; ++$j) {
        echo $j;
    }
    echo ("<br/>");
}
for($i=2; $i<=4; ++$i) {
    for($j=2; $j<=$i; ++$j) {
        echo $j;
    }
    echo ("<br/>");
}

I don't know how to recycle to the first number after the max number is reached. Since my max number is 4, 1 should used instead of 5 (and 2 for 6 and 3 for 7).


Solution

  • You loop from 1 to 4, and subtract 4 if the value is bigger than 4.

    This is for 2, 23, 234, 2341:

    for ($i = 1; $i <= 4; $i++) {
      for ($j = 1; $j <= $i; $j++) {
        $value = $j + 1;   // or +2, or +3
        echo $value > 4 ? $value - 4 : $value;
      }
      echo "\n";
    }
    

    And this would generate all output within one big loop:

    $max = 4;
    
    for ($start = 0; $start < $max; $start++) {
      for ($i = 1; $i <= $max; $i++) {
        for ($j = 1; $j <= $i; $j++) {
          $value = $j + $start;
          echo $value > $max ? $value - $max : $value;
        }
        echo "\n";
      }
    }