-
Notifications
You must be signed in to change notification settings - Fork 1
/
construction_game.php
113 lines (100 loc) · 2.67 KB
/
construction_game.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
<?php
class ConstructionGame
{
private $length;
private $width;
private $table;
public function __construct(int $length, int $width)
{
$this->length = $length;
$this->width = $width;
$this->table = array_fill(0, $length, array_fill(0, $width, 0));
}
public function addCubes(array $cubes): void
{
for ($i = 0; $i < $this->length; $i++) {
for ($j = 0; $j < $this->width; $j++) {
if ($cubes[$i][$j]) {
$this->table[$i][$j]++;
}
}
}
// Clear full layers
$this->clearFullLayers();
}
private function clearFullLayers(): void
{
$maxHeight = $this->getHeight();
for ($h = $maxHeight; $h > 0; $h--) {
$fullLayer = true;
for ($i = 0; $i < $this->length; $i++) {
for ($j = 0; $j < $this->width; $j++) {
if ($this->table[$i][$j] < $h) {
$fullLayer = false;
break 2; // Break both loops
}
}
}
if ($fullLayer) {
// Clear the full layer by reducing height
for ($i = 0; $i < $this->length; $i++) {
for ($j = 0; $j < $this->width; $j++) {
if ($this->table[$i][$j] >= $h) {
$this->table[$i][$j]--;
}
}
}
}
}
}
public function getHeight(): int
{
$maxHeight = 0;
foreach ($this->table as $row) {
foreach ($row as $height) {
if ($height > $maxHeight) {
$maxHeight = $height;
}
}
}
return $maxHeight;
}
}
// Example usage
$game = new ConstructionGame(2, 2);
// Test case 1
$game->addCubes([
[true, true],
[false, false]
]);
$game->addCubes([
[true, true],
[false, true]
]);
echo $game->getHeight() . "\n"; // should print 2
// Test case 2
$game->addCubes([
[false, false],
[true, true]
]);
echo $game->getHeight() . "\n"; // should print 1
// Additional test case
$game2 = new ConstructionGame(3, 3);
$game2->addCubes([
[true, true, true],
[false, false, false],
[false, false, false]
]);
echo $game2->getHeight() . "\n"; // should print 1
$game2->addCubes([
[false, false, false],
[true, true, true],
[false, false, false]
]);
echo $game2->getHeight() . "\n"; // should print 2
$game2->addCubes([
[false, false, false],
[false, false, false],
[true, true, true]
]);
echo $game2->getHeight() . "\n"; // should print 1