53 lines
1.6 KiB
PHP
53 lines
1.6 KiB
PHP
|
<?php
|
||
|
|
||
|
$lines = array_map('str_split', explode("\n", file_get_contents('input.txt')));
|
||
|
|
||
|
$oxygen_lines = $lines;
|
||
|
for ($i = 0, $l = count($oxygen_lines[0]); $i < $l; $i++) {
|
||
|
if (count($oxygen_lines) <= 1) {
|
||
|
break;
|
||
|
}
|
||
|
$rotated_lines = array_map('array_reverse', array_map(null, ...$oxygen_lines)); // matrix rotation
|
||
|
$max = determine_max_number_at_line($rotated_lines, $i);
|
||
|
$oxygen_lines = array_filter($oxygen_lines, static function ($line) use ($max, $i) {
|
||
|
return $line[$i] == $max;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
$co2_lines = $lines;
|
||
|
for ($i = 0, $l = count($co2_lines[0]); $i < $l; $i++) {
|
||
|
if (count($co2_lines) <= 1) {
|
||
|
break;
|
||
|
}
|
||
|
$rotated_lines = array_map('array_reverse', array_map(null, ...$co2_lines)); // matrix rotation
|
||
|
$min = determine_min_number_at_line($rotated_lines, $i);
|
||
|
$co2_lines = array_filter($co2_lines, static function ($line) use ($min, $i) {
|
||
|
return $line[$i] == $min;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
$oxygen = implode(current($oxygen_lines));
|
||
|
$co2 = implode(current($co2_lines));
|
||
|
|
||
|
echo bindec($oxygen) * bindec($co2);
|
||
|
|
||
|
function determine_max_number_at_line($rotated_lines, $line_number): bool|int|string
|
||
|
{
|
||
|
$line = $rotated_lines[$line_number];
|
||
|
$counts = array_count_values($line);
|
||
|
if ($counts[0] === $counts[1]) {
|
||
|
return 1;
|
||
|
}
|
||
|
return array_search(max($counts), $counts);
|
||
|
}
|
||
|
|
||
|
function determine_min_number_at_line($rotated_lines, $line_number): bool|int|string
|
||
|
{
|
||
|
$line = $rotated_lines[$line_number];
|
||
|
$counts = array_count_values($line);
|
||
|
if ($counts[0] === $counts[1]) {
|
||
|
return 0;
|
||
|
}
|
||
|
return array_search(min($counts), $counts);
|
||
|
}
|