43 lines
1 KiB
PHP
43 lines
1 KiB
PHP
<?php
|
|
$input_file = '../inputs/day15.txt';
|
|
if (file_exists($input_file)) {
|
|
$input = file_get_contents($input_file);
|
|
if ($input != null) {
|
|
$numbers = array_map('trim', explode(',', $input));
|
|
print 'Part 1 answer: ' . solve_part_one($numbers) . "\n";
|
|
print 'Part 2 answer: ' . solve_part_two($numbers) . "\n";
|
|
}
|
|
}
|
|
|
|
function solve_part_one(array $numbers): int
|
|
{
|
|
return get_number_in_sequence($numbers, 2020);
|
|
}
|
|
|
|
function solve_part_two(array $numbers): int
|
|
{
|
|
ini_set('memory_limit', '-1');
|
|
return get_number_in_sequence($numbers, 30000000);
|
|
}
|
|
|
|
function get_number_in_sequence(array $initial_numbers, int $num): int
|
|
{
|
|
$last_spoken = [];
|
|
foreach ($initial_numbers as $turn => $number)
|
|
$last_spoken[(int)$number] = (int)$turn + 1;
|
|
|
|
$last = array_keys($last_spoken)[count($last_spoken) - 1];
|
|
|
|
for ($i = count($last_spoken); $i < $num; $i++) {
|
|
if (array_key_exists($last, $last_spoken)) {
|
|
$prev = $last;
|
|
$last = $i - $last_spoken[$last];
|
|
$last_spoken[$prev] = $i;
|
|
} else {
|
|
$last_spoken[$last] = $i;
|
|
$last = 0;
|
|
}
|
|
}
|
|
|
|
return $last;
|
|
}
|