advent_of_code_2020/day_15/part_2.php
2020-12-15 10:15:27 +01:00

40 lines
999 B
PHP

<?php
$starting_numbers = explode(',', file_get_contents('input.txt'));
$tmp_numbers = array_map('intval', $starting_numbers);
$count_numbers = [];
foreach ($tmp_numbers as $i => $tmp_number) {
if (array_key_exists($tmp_number, $count_numbers)) {
$count_numbers[$tmp_number][] = $i;
} else {
$count_numbers[$tmp_number] = [$i];
}
}
$number = end($tmp_numbers);
unset($tmp_numbers, $tmp_number);
for ($i = count($starting_numbers); $i <= 29999999; $i++) {
$number = newNumber($i, $number);
}
echo $number;
function newNumber(int $i, int $number = 0)
{
global $count_numbers;
if (!array_key_exists($number, $count_numbers)) {
$count_numbers[$number] = [$i];
return $number;
}
$count_indexes = count($count_numbers[$number]);
$new_number = $count_indexes === 1 ? 0 : $count_numbers[$number][$count_indexes - 1] - $count_numbers[$number][$count_indexes - 2];
$count_numbers[$new_number][] = $i;
return $new_number;
}