60 lines
911 B
PHP
60 lines
911 B
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;
|
||
|
}
|
||
|
|
||
|
[$list1, $list2] = parseLists();
|
||
|
|
||
|
$sumOfDifference = diffSum($list1, $list2);
|
||
|
|
||
|
echo "Part 1: Total distance: $sumOfDifference\n";
|
||
|
|