Skip to content

Instantly share code, notes, and snippets.

@proclnas
Last active March 8, 2017 21:48
Show Gist options
  • Save proclnas/f3bcfe9504e99e8d0dbd501927352b11 to your computer and use it in GitHub Desktop.
Save proclnas/f3bcfe9504e99e8d0dbd501927352b11 to your computer and use it in GitHub Desktop.
<?php
/**
*
* A snake matrix is a square matrix that follows this pattern:
*
* 3-by-3:
* 1 2 3
* 6 5 4
* 7 8 9
* and 4-by-4:
*
* 1 2 3 4
* 8 7 6 5
* 9 10 11 12
* 16 15 14 13
*/
<?php
$cols = 4;
$arr = range(1, 20);
(function() use ($cols, $arr){
$chunks = array_chunk($arr, $cols);
$counter = 1;
$snakeMatrix = array_map(
function($chunk) use (&$counter) {
if (!($counter & 1)) {
$counter++;
return array_reverse($chunk);
}
$counter++;
return $chunk;
}, $chunks);
foreach ($snakeMatrix as $numbers) {
foreach ($numbers as $n)
echo sprintf("%-5s", $n);
echo PHP_EOL;
}
})();
@proclnas
Copy link
Author

proclnas commented Mar 8, 2017

Output:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment