-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem28.php
156 lines (130 loc) · 3.15 KB
/
Problem28.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?php
declare(strict_types=1);
namespace ProjectEuler;
$problem = new Problem28();
$problem->handle();
class Problem28
{
public int $size = 5;
public int $x = 0;
public int $y = 0;
public int $n = 0;
public array $matrix = [];
public function handle(): void
{
$this->setup();
$this->buildMatrix();
if (php_sapi_name() !== 'cli') {
$this->display();
} else {
$this->addDiagonals();
}
}
private function setup(): void
{
$this->matrix = $this->setGrid();
$this->x = array_key_last($this->matrix[0]);
$this->y = 0;
$this->n = $this->size ** 2;
}
private function setGrid(): array
{
$matrix = [];
for ($x = 0; $x < $this->size; $x++) {
for ($y = 0; $y < $this->size; $y++) {
$matrix[$x][$y] = 0;
}
}
return $matrix;
}
public function buildMatrix(): void
{
while ($this->n > 0) {
$this->goLeft();
$this->goDown();
$this->goRight();
$this->goUp();
}
}
private function goLeft(): void
{
while ($this->spotIsFree()) {
$this->matrix[$this->y][$this->x] = $this->n;
$this->x--;
$this->n--;
if ($this->n == 0) {
return;
}
}
$this->y++;
$this->x++;
}
private function spotIsFree(): bool
{
return isset($this->matrix[$this->y][$this->x]) && $this->matrix[$this->y][$this->x] == 0;
}
private function goDown(): void
{
while ($this->spotIsFree()) {
$this->matrix[$this->y][$this->x] = $this->n;
$this->y++;
$this->n--;
if ($this->n == 0) {
return;
}
}
$this->x++;
$this->y--;
}
private function goRight(): void
{
while ($this->spotIsFree()) {
$this->matrix[$this->y][$this->x] = $this->n;
$this->x++;
$this->n--;
if ($this->n == 0) {
return;
}
}
$this->x--;
$this->y--;
}
private function goUp(): void
{
while ($this->spotIsFree()) {
$this->matrix[$this->y][$this->x] = $this->n;
$this->y--;
$this->n--;
if ($this->n == 0) {
return;
}
}
$this->x--;
$this->y++;
}
private function display(): void
{
echo '<style>
body{padding-left:50px;}
</style>';
foreach ($this->matrix as $y) {
foreach ($y as $x) {
echo $x . "\t";
}
echo PHP_EOL;
}
}
private function addDiagonals(): void
{
$sum = -1;
for ($i = 0; $i < count($this->matrix[0]); $i++) {
$sum += $this->matrix[$i][$i];
}
$x = 0;
for ($y = $this->size - 1; $y >= 0; $y--) {
$sum += $this->matrix[$y][$x];
$x++;
}
echo "Answer is: $sum\n";
}
}