You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
784 B

2 weeks ago
<?php
final class Day1 extends Day {
function part1(): string {
$left = [];
$right = [];
foreach ($this->input as $line){
[$left[], $right[]] = array_map("intval", explode(" ", $line));
}
sort($left);
sort($right);
$sum = 0;
for ($i = 0; $i < count($left); $i++){
$sum += abs($left[$i] - $right[$i]);
}
return strval($sum);
}
function part2(): string {
$left = [];
$rightCounts = [];
foreach ($this->input as $line){
[$left[], $right] = array_map("intval", explode(" ", $line));
if (array_key_exists($right, $rightCounts)){
$rightCounts[$right]++;
} else {
$rightCounts[$right] = 1;
}
}
$sum = 0;
foreach ($left as $number){
$sum += $number * ($rightCounts[$number] ?? 0);
}
return strval($sum);
}
}