-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay10.php
109 lines (91 loc) · 2.65 KB
/
Day10.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
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2021\Solutions\Day10;
use RuntimeException;
use XonneX\AdventOfCode\Core\AbstractSolution;
use function array_pop;
use function explode;
use function implode;
use function in_array;
use function print_r;
use function sort;
use function str_split;
use function var_dump;
use const PHP_EOL;
class Day10 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2021, 10);
}
protected function partOne(string $input): string
{
$charMap = [
'(' => ')',
'[' => ']',
'{' => '}',
'<' => '>',
];
$points = 0;
foreach (explode("\n", $input) as $line) {
$chunkStarts = [];
foreach (str_split($line) as $char) {
if (in_array($char, ['[', '(', '<', '{'])) {
$chunkStarts[] = $char;
continue;
}
$chunkStart = array_pop($chunkStarts);
if ($charMap[$chunkStart] !== $char) {
if ($char === ')') {
$points += 3;
} elseif ($char === ']') {
$points += 57;
} elseif ($char === '}') {
$points += 1197;
} elseif ($char === '>') {
$points += 25137;
}
}
}
}
return (string) $points;
}
protected function partTwo(string $input): string
{
$charMap = [
'(' => ')',
'[' => ']',
'{' => '}',
'<' => '>',
];
$valueMap = [
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
];
$scores = [];
$lines = explode("\n", $input);
foreach ($lines as $key => $line) {
$chunkStarts = [];
foreach (str_split($line) as $char) {
if (in_array($char, ['[', '(', '<', '{'])) {
$chunkStarts[] = $char;
continue;
}
$chunkStart = array_pop($chunkStarts);
if ($charMap[$chunkStart] !== $char) {
continue 2;
}
}
$totalScore = 0;
while (($chunkStart = array_pop($chunkStarts)) !== null) {
$totalScore *= 5;
$totalScore += $valueMap[$charMap[$chunkStart]];
}
$scores[] = $totalScore;
}
sort($scores);
return (string) $scores[(count($scores) - 1) / 2];
}
}