-
Notifications
You must be signed in to change notification settings - Fork 8
/
squareNumbers.php
executable file
·103 lines (88 loc) · 2.01 KB
/
squareNumbers.php
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
$size = $argv[1];
function row($size){
print " row: $size * $size\n";
$total = $size * $size;
$current = $size;
for ($i=1; $i <= $total; $i++) {
print sprintf(" %'.02d"," $i");
if($i == $current) {
$current += $size;
print "\n";
}
}
}
function column($size){
print " column: $size * $size\n";
$total = $size * $size;
$counter = $size;
for ($i=1; $i <= $size ; $i++) {
print sprintf(" %'.02d"," $i");
$current = $i;
for ($j=1; $j < $counter ; $j++) {
$current += $size;
print sprintf(" %'.02d"," $current");
}
print"\n";
}
}
function spiral($size){
$square = $size * $size;
$array = [];
for($i = 0; $i < $size; $i++) {
$array[$i] = [];
for($j = 0; $j < $size; $j++) {
$array[$i][$j] = 0;
}
}
$x = $size -1;
$y = 0;
$dx = -1;
$dy = 0;
for($i = $square; $i > 0; $i--) {
$array[$y][$x] = "$i $x $y";
$new_x = $x + $dx;
$new_y = $y + $dy;
if ($new_x >= 0 && $new_x < $size && $new_y >= 0 && $new_y < $size && !($array[$new_y][$new_x])){
$x = $new_x;
$y = $new_y;
} else {
$res = turn($dx, $dy);
$dx = $res[0];
$dy = $res[1];
$x = $x + $dx;
$y = $y + $dy;
}
}
// print_r($array);
echo (" spiral: $size * $size\n");
foreach($array as $line) {
foreach($line as $v) {
printf(" %02d", $v);
}
printf("\n");
}
}
function turn($dx, $dy){
if ($dx === 0 && $dy === -1) { // UP
$dx = -1; // LEFT
$dy = 0;
} elseif ($dx === 1 && $dy === 0) { // RIGHT
$dx = 0; // UP
$dy = -1;
} elseif ($dx === 0 && $dy === 1) { // DOWN
$dx = 1; // RIGHT
$dy = 0;
} elseif($dx === -1 && $dy === 0) { // LEFT
$dx = 0; // DOWN
$dy = 1;
} else {
die('yolo');
}
return [$dx, $dy];
}
row($size);
print "\n\n";
column($size);
print "\n\n";
spiral($size);