-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateMatrix.php
More file actions
51 lines (48 loc) · 1.17 KB
/
generateMatrix.php
File metadata and controls
51 lines (48 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
function generateMatrix($a)
{
$n = $a;
$matrix = array();
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
$matrix[$i][$j] = 0;
}
}
$i = 1;
$top = 0;
$bottom = $n - 1;
$left = 0;
$ritht = $n - 1;
$direction = 0;
while ($i <= $n * $n) {
if ($direction == 0) {
for ($j = $left; $j <= $ritht; $j++) {
$matrix[$top][$j] = $i++;
}
$top++;
} elseif ($direction == 1) {
for ($j = $top; $j <= $bottom; $j++) {
$matrix[$j][$ritht] = $i++;
}
$ritht--;
} elseif ($direction == 2) {
for ($j = $ritht; $j >= $left; $j--) {
$matrix[$bottom][$j] = $i++;
}
$bottom--;
} else {
for ($j = $bottom; $j >= $top; $j--) {
$matrix[$j][$left] = $i++;
}
$left++;
}
$direction = ($direction + 1) % 4;
}
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
echo $matrix[$i][$j] . " ";
}
echo "<br/>";
}
}
generateMatrix(3);