fork download
  1. <?php
  2. function draw_pattern($rows, $cols) {
  3. for ($row = 0; $row < $rows; $row++) {
  4. for ($col = 0; $col < $cols; $col++) {
  5. if ($row % 2 === 0) {
  6. // $row * $cols + 1 gives you first number for that row
  7. // e.g. for row number 2 you get 2 * 4 + 1 = 9
  8. $num = $row * $cols + 1 + $col;
  9. } else {
  10. // ($row + 1) * $cols gives you last number for that row
  11. // e.g. for row number 1 you get (1 + 1) * 4 = 8
  12. $num = ($row + 1) * $cols - $col;
  13. }
  14. echo sprintf('%2d ', $num);
  15. }
  16. echo PHP_EOL;
  17. }
  18. }
  19. draw_pattern(3, 4);
  20. echo PHP_EOL;
  21. draw_pattern(4, 5);
  22. echo PHP_EOL;
  23. draw_pattern(5, 6);
  24.  
Success #stdin #stdout 0s 82560KB
stdin
Standard input is empty
stdout
 1  2  3  4 
 8  7  6  5 
 9 10 11 12 

 1  2  3  4  5 
10  9  8  7  6 
11 12 13 14 15 
20 19 18 17 16 

 1  2  3  4  5  6 
12 11 10  9  8  7 
13 14 15 16 17 18 
24 23 22 21 20 19 
25 26 27 28 29 30