advent_of_code_2021/day_10/part_2.php
2021-12-10 09:24:39 +01:00

47 lines
1.1 KiB
PHP

<?php
$lines = explode("\n", file_get_contents('./input.txt'));
$coolos = [];
foreach ($lines as $line) {
$chunks = [];
$is_cool = true;
foreach (str_split($line) as $chunk) {
switch ($chunk) {
case '(': $chunks[] = ')';break;
case '[': $chunks[] = ']';break;
case '{': $chunks[] = '}';break;
case '<': $chunks[] = '>';break;
default:
$last_chunk = array_pop($chunks);
if ($last_chunk !== $chunk) {
$is_cool = false;
break 2;
}
}
}
if ($is_cool) {
$coolos[] = $chunks;
}
}
$scores = [];
foreach ($coolos as $remaining_chunks) {
$remaining_chunks = array_reverse($remaining_chunks);
$scores[] = array_reduce($remaining_chunks, static function ($carry, $chunk) {
$additions = [
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
];
$carry *= 5;
$carry += $additions[$chunk];
return $carry;
});
}
sort($scores);
echo $scores[(int) floor(count($scores) / 2)];