Last active
March 8, 2017 21:48
-
-
Save proclnas/f3bcfe9504e99e8d0dbd501927352b11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: