-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay2.php
72 lines (60 loc) · 2.21 KB
/
Day2.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
<?php
declare(strict_types=1);
namespace App;
use App\Contracts\DayBehaviour;
class Day2 extends DayBehaviour
{
/**
* Refactored this using collect, which seems a few orders of magnitude slower :(
* Mem[616kb] Peak[ 1013kb] Time[0.06339s] <-- Using collect()
* Mem[422kb] Peak[ 925kb] Time[0.00072s] <-- Using commented out array functionality.
*/
public function solvePart1(): ?int
{
$pos = collect($this->input)
->reduce(function (array $pos, string $cmd) {
[$instruction, $value] = explode(' ', $cmd);
match ($instruction) {
'forward' => $pos['hoz'] += (int) $value,
'down' => $pos['dep'] += (int) $value,
'up' => $pos['dep'] -= (int) $value,
};
return $pos;
}, ['hoz' => 0, 'dep' => 0]);
return $pos['hoz'] * $pos['dep'];
/*$input = array_map(fn (string $line) => explode(' ', $line), $this->input);
$pos = [
'hoz' => 0,
'dep' => 0,
];
foreach ($input as [$instruction, $value]) {
match ($instruction) {
'forward' => $pos['hoz'] += (int) $value,
'down' => $pos['dep'] += (int) $value,
'up' => $pos['dep'] -= (int) $value,
};
}
return $pos['hoz'] * $pos['dep'];*/
}
public function solvePart2(): ?int
{
$pos = collect($this->input)
->reduce(function (array $pos, string $cmd) {
[$instruction, $value] = explode(' ', $cmd);
switch ($instruction) {
case 'forward':
$pos['hoz'] += (int) $value;
$pos['dep'] += (int) $value * $pos['aim'];
break;
case 'down':
$pos['aim'] += (int) $value;
break;
case 'up':
$pos['aim'] -= (int) $value;
break;
}
return $pos;
}, ['hoz' => 0, 'dep' => 0, 'aim' => 0]);
return $pos['hoz'] * $pos['dep'];
}
}