advent-of-code/2024/day1/index.php

72 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2024-12-03 13:56:49 -05:00
<?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;
}
2024-12-03 14:59:53 -05:00
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;
}
2024-12-03 13:56:49 -05:00
[$list1, $list2] = parseLists();
$sumOfDifference = diffSum($list1, $list2);
2024-12-03 14:59:53 -05:00
$similarityScore = similarityScore($list1, $list2);
2024-12-03 13:56:49 -05:00
echo "Part 1: Total distance: $sumOfDifference\n";
2024-12-03 14:59:53 -05:00
echo "Part 2: Similarity score: $similarityScore\n";