1
0
Fork 0
advent-of-code/2020/day9.php

75 lines
1.6 KiB
PHP
Raw Permalink Normal View History

2024-02-08 09:55:40 +01:00
<?php
use JetBrains\PhpStorm\Pure;
$input_file = '../inputs/day9.txt';
if (file_exists($input_file)) {
$input = file_get_contents($input_file);
if ($input != null) {
$preamble = 25;
$numbers = array_map('trim', explode("\n", $input));
print 'Part 1 answer: ' . solve_part_one($numbers, $preamble) . "\n";
print 'Part 2 answer: ' . solve_part_two($numbers, $preamble) . "\n";
}
}
#[Pure] function solve_part_one(array $numbers, int $preamble): int
{
return get_first_error($numbers, $preamble);
}
function solve_part_two(array $numbers, int $preamble): int
{
return get_weakness($numbers, get_first_error($numbers, $preamble));
}
function get_first_error(array $numbers, int $preamble): int
{
$error = 0;
for ($i = $preamble; $i < count($numbers); $i++) {
$correctly_encoded = false;
for ($j = $i - $preamble; $j < $i; $j++) {
for ($k = $i - $preamble; $k < $i; $k++) {
if ($numbers[$j] + $numbers[$k] == $numbers[$i]) {
$correctly_encoded = true;
break;
}
}
if ($correctly_encoded)
break;
}
if ($correctly_encoded === false) {
return $numbers[$i];
}
}
return $error;
}
function get_weakness(array $numbers, int $result): int
{
$min_pos = 0;
$length = 2;
while ($min_pos < count($numbers)) {
while ($length < count($numbers) - 2) {
$test = array_slice($numbers, $min_pos, $length);
if (array_sum($test) == $result) {
sort($test);
return $test[0] + $test[count($test) - 1];
} else if (array_sum($test) > $result) {
$min_pos += 1;
$length = 2;
break;
}
$length += 1;
}
}
return 0;
}