57 lines
1.4 KiB
PHP
57 lines
1.4 KiB
PHP
<?php
|
|
$input_file = '../inputs/day10.txt';
|
|
if (file_exists($input_file)) {
|
|
$input = file_get_contents($input_file);
|
|
if ($input != null) {
|
|
$joltages = array_map('trim', explode("\n", $input));
|
|
print 'Part 1 answer: ' . solve_part_one($joltages) . "\n";
|
|
print 'Part 2 answer: ' . solve_part_two($joltages) . "\n";
|
|
}
|
|
}
|
|
|
|
function solve_part_one(array $joltages): int
|
|
{
|
|
$sorted_joltages = $joltages;
|
|
$sorted_joltages[] = "0";
|
|
sort($sorted_joltages);
|
|
$sorted_joltages[] = $sorted_joltages[count($sorted_joltages) - 1] + 3;
|
|
$differences = chain_adapters($sorted_joltages);
|
|
return $differences[0] * $differences[2];
|
|
}
|
|
|
|
function solve_part_two(array $joltages): int
|
|
{
|
|
$sorted_joltages = $joltages;
|
|
$sorted_joltages[] = "0";
|
|
sort($sorted_joltages);
|
|
$sorted_joltages[] = $sorted_joltages[count($sorted_joltages) - 1] + 3;
|
|
return get_max_chains($sorted_joltages);
|
|
}
|
|
|
|
function chain_adapters(array $joltages): array
|
|
{
|
|
$differences = [0, 0, 0];
|
|
|
|
for ($i = 1; $i < count($joltages); $i++) {
|
|
$diff = $joltages[$i] - $joltages[$i - 1];
|
|
$differences[$diff - 1] += 1;
|
|
}
|
|
|
|
return $differences;
|
|
}
|
|
|
|
function get_max_chains(array $joltages): int
|
|
{
|
|
$jolt_count = count($joltages);
|
|
$memo = [$jolt_count - 1 => 1];
|
|
|
|
for ($i = $jolt_count - 2; $i >= 0; $i--) {
|
|
$count = 0;
|
|
for ($j = $i + 1; $j < $jolt_count && $joltages[$j] - $joltages[$i] <= 3; $j++) {
|
|
$count += $memo[$j];
|
|
}
|
|
$memo[$i] = $count;
|
|
}
|
|
|
|
return $memo[0];
|
|
}
|