73 lines
1.6 KiB
PHP
73 lines
1.6 KiB
PHP
<?php
|
|
$input_file = '../inputs/day5.txt';
|
|
if (file_exists($input_file)) {
|
|
$input = file_get_contents($input_file);
|
|
if ($input != null) {
|
|
$passes = explode("\n", $input);
|
|
print 'Part 1 answer: ' . solve_part_one($passes) . "\n";
|
|
print 'Part 2 answer: ' . solve_part_two($passes) . "\n";
|
|
}
|
|
}
|
|
|
|
function solve_part_one(array $passes): int
|
|
{
|
|
$valid_passes = parse_passes($passes);
|
|
$max_pass = 0;
|
|
|
|
foreach ($valid_passes as $pass)
|
|
if ($pass[2] > $max_pass)
|
|
$max_pass = $pass[2];
|
|
|
|
return $max_pass;
|
|
}
|
|
|
|
function solve_part_two(array $passes): int
|
|
{
|
|
$valid_passes = parse_passes($passes);
|
|
$sorted_ids = array_map(fn ($pass) => $pass[2], $valid_passes);
|
|
sort($sorted_ids);
|
|
|
|
for ($i = 0; $i < count($sorted_ids); $i++)
|
|
if ($sorted_ids[$i] - $sorted_ids[0] != $i)
|
|
return $sorted_ids[$i] - 1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
function parse_passes(array $passes): array
|
|
{
|
|
$parsed_passes = [];
|
|
|
|
foreach ($passes as $pass) {
|
|
if (preg_match('/^([FB]{7})([LR]{3})$/', trim($pass), $matches) > 0) {
|
|
$min_row = 0;
|
|
$max_row = 127;
|
|
$min_col = 0;
|
|
$max_col = 7;
|
|
|
|
for ($i = 0; $i < strlen($matches[1]); $i++) {
|
|
$tot_rows = $max_row + 1 - $min_row;
|
|
$new_tot_rows = $tot_rows / 2;
|
|
if ($matches[1][$i] === 'F') {
|
|
$max_row -= $new_tot_rows;
|
|
} else {
|
|
$min_row += $new_tot_rows;
|
|
}
|
|
}
|
|
|
|
for ($i = 0; $i < strlen($matches[2]); $i++) {
|
|
$tot_cols = $max_col + 1 - $min_col;
|
|
$new_tot_cols = $tot_cols / 2;
|
|
if ($matches[2][$i] === 'L') {
|
|
$max_col -= $new_tot_cols;
|
|
} else {
|
|
$min_col += $new_tot_cols;
|
|
}
|
|
}
|
|
|
|
$parsed_passes[] = [$min_row, $min_col, $min_row * 8 + $min_col];
|
|
}
|
|
}
|
|
|
|
return $parsed_passes;
|
|
}
|