1

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).

2 Answers 2

2

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";
  }
}
0
1

Whenever you need circular array access, it is a good idea to implement a modulus calculation. To set this up, use a range between 0 and 3 instead of using 1 and 4. A modulus calculation can return a 0 result, so the formula must be prepared to handle this value. To adjust the value, just add 1 after the modulus calculation to generate numbers between 1 and 4.

Accumulate strings of numbers as desired and reset the string upon each start of the outer loop.

Below proves that you do not need three nested loops for this task.

Code: (Demo)

for ($i = 0; $i < 4; ++$i) {
    for ($s = '', $j = 0; $j < 4; ++$j) {
        $s .= ($i + $j) % 4 + 1;
        echo $s . "\n";
    }
}

Output:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.