Last active
November 1, 2016 07:11
-
-
Save f3ath/6482570d80773b48bd37630e21fa2ad8 to your computer and use it in GitHub Desktop.
This file contains 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 | |
function spiral(array $m) | |
{ | |
$x_max = sizeof($m) - 1; | |
if ($x_max < 1) { | |
return; | |
} | |
$y_max = sizeof($m[0]) - 1; | |
if ($y_max < 1) { | |
return; | |
} | |
$x_min = $y_min = $dir = 0; | |
while ($y_min <= $y_max && $x_min <= $x_max) { | |
switch ($dir = $dir++ %4) { | |
case 0: // right | |
for ($y = $y_min; $y <= $y_max; $y++) { | |
yield $m[$x_min][$y]; | |
} | |
$x_min++; | |
break; | |
case 1: // down | |
for ($x = $x_min; $x <= $x_max; $x++) { | |
yield $m[$x][$y_max]; | |
} | |
$y_max--; | |
break; | |
case 2: // left | |
for ($y = $y_max; $y >= $y_min; $y--) { | |
yield $m[$x_max][$y]; | |
} | |
$x_max--; | |
break; | |
case 3: // up | |
for ($x = $x_max; $x >= $x_min; $x--) { | |
yield $m[$x][$y_min]; | |
} | |
$y_min++; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment