Last active
August 29, 2015 14:21
-
-
Save vitaliy-evsyukov/c631405cd13978ffad01 to your computer and use it in GitHub Desktop.
Spiral matrix traversal in PHP (see in action http://sandbox.onlinephpfunctions.com/code/a0caf944a35488c99722f8ab9947bf85bb6bdbc7)
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
$a = [ | |
[1, 2, 3, 4], | |
[14, 15, 16, 5], | |
[13, 20, 17, 6], | |
[12, 19, 18, 7], | |
[11, 10, 9, 8] | |
]; | |
$r1 = rand(0, 7); | |
$r2 = rand(0, 7); | |
$a = []; | |
for ($i = 0; $i < $r1; $i++) { | |
for ($j = 0; $j < $r2; $j++) { | |
$a[$i][$j] = rand(1, 10); | |
} | |
} | |
$r = []; | |
for ($i = 0; $i < $r1; $i++) { | |
$t = []; | |
for ($j = 0; $j < $r2; $j++) { | |
$t[] = $a[$i][$j]; | |
} | |
$r[] = '[' . implode(', ', $t) . ']'; | |
} | |
echo "[\n" . implode(",\n", $r) . "\n];\n\n"; | |
/** | |
some examples of array | |
$a = [ | |
[6, 10, 9], | |
[3, 5, 2], | |
[8, 2, 5], | |
[4, 1, 8], | |
[6, 10, 5], | |
[6, 8, 10] | |
]; | |
$a = [ | |
[1, 2, 3, 4], | |
[14, 15, 16, 5], | |
[13, 20, 17, 6], | |
[12, 19, 18, 7], | |
[11, 10, 9, 8] | |
]; | |
*/ | |
$rows = sizeof($a); | |
if ($rows) { | |
$cols = sizeof($a[0]); | |
} else { | |
$cols = 0; | |
} | |
// how much elements can be traversed | |
$total = $rows * $cols; | |
// limit, cols or rows | |
$i = $cols; | |
// mode, string 'rows' or 'cols' for toggle $i variable | |
$d = 'cols'; | |
// counter of edge (cols edge or rows edge) | |
$j = 0; | |
// counter of items | |
$c = 0; | |
// coordinates of cell ($y is row, $x is column) | |
$x = 0; | |
$y = 0; | |
// delta for coordinates | |
$dy = 0; | |
$dx = 1; | |
// resulting array | |
$r = []; | |
while ($c < $total) { | |
// add data to result | |
$r[] = $a[$y][$x]; | |
// increment counter of edge | |
$j++; | |
// if we finished traversing over current edge | |
if ($j === $i) { | |
// reset counter | |
$j = 0; | |
// swap direction deltas (1, 0) -> (0, 1) -> (-1, 0) -> (0, -1) -> (1, 0) -> ... | |
list($dx, $dy) = [-$dy, $dx]; | |
// if it's last column in edge, decrement rows (because we are in some (last or first) row now, huh) and change mode | |
if ($d === 'cols') { | |
$rows--; | |
$i = $rows; | |
$d = 'rows'; | |
} else { | |
// if it's last row in edge, decrement columns (because we are in some column now) and also change mode | |
$cols--; | |
$i = $cols; | |
$d = 'cols'; | |
} | |
} | |
// change cell coordinates by delta | |
$x = $x + $dx; $y = $y + $dy; | |
// increment main counter | |
$c++; | |
} | |
if (empty($r)) echo "Empty result\n"; | |
echo implode(' ', $r); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment