advent-of-code/2024/day1/index.php
2024-12-03 14:59:53 -05:00

72 lines
1.2 KiB
PHP

<?php declare(strict_types=1);
function readLines (): array
{
$fp = fopen("./input.txt", 'r');
$lines = [];
if ($fp)
{
while (($buffer = fgets($fp)))
{
$lines[] = $buffer;
}
fclose($fp);
}
return $lines;
}
function parseLists (): array
{
$arr1 = [];
$arr2 = [];
$lines = readLines();
echo "Number of input lines: " . count($lines) . "\n";
foreach ($lines as $line)
{
[$entry1, $entry2] = explode(' ', $line);
$arr1[] = (int)$entry1;
$arr2[] = (int)$entry2;
}
return [$arr1, $arr2];
}
function diffSum (array $list1, array $list2): int
{
sort($list1, SORT_NUMERIC);
sort($list2, SORT_NUMERIC);
$total = count($list1);
$sum = 0;
for ($i = 0; $i < $total; $i++)
{
$sum += abs($list1[$i] - $list2[$i]);
}
return $sum;
}
function similarityScore (array $list1, array $list2): int
{
$sum = 0;
foreach ($list1 as $search)
{
$rightList = array_filter($list2, fn (int $item) => $item === $search);
$sum += ($search * count($rightList));
}
return $sum;
}
[$list1, $list2] = parseLists();
$sumOfDifference = diffSum($list1, $list2);
$similarityScore = similarityScore($list1, $list2);
echo "Part 1: Total distance: $sumOfDifference\n";
echo "Part 2: Similarity score: $similarityScore\n";