// Remove all matching pairs
$lines = $input->lines->map(function ($line) {
$pairs = ["[]", "()", "{}", "<>"];
for ($i = 0; $i < $line->length() / 2 + 2; $i++) {
$line = $line->replace($pairs, "");
}
return $line;
});
// ==================================================
// > PART 1
// ==================================================
$invalid = $lines->map(fn ($line) => [
")" => 3,
"]" => 57,
"}" => 1197,
">" => 25137,
][$line->match("/[\)\]\}\>]/")[0] ?? null] ?? 0);
$solution_1 = $invalid->sum();
// ==================================================
// > PART 2
// ==================================================
$incomplete = $lines->removeKeys($invalid->filter()->keys());
$scores = $incomplete->map(fn ($open) =>
$open->chars()->reverse()->reduce(fn ($score, $open) =>
($score * 5) + [
"(" => 1,
"[" => 2,
"{" => 3,
"<" => 4,
][$open]
, 0)
);
$solution_2 = $scores->sort()->values()[floor($scores->count() / 2)];