1
0
Fork 0
advent-of-code/2021/day3.php

122 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2024-02-08 09:55:40 +01:00
<?php
$input_file = '../inputs/day3.txt';
if (file_exists($input_file)) {
$input = file_get_contents($input_file);
if ($input != null) {
$binaries = array_map(fn ($str) => trim($str), explode("\n", $input));
print 'Part 1 answer: ' . solve_part_one($binaries) . "\n";
print 'Part 2 answer: ' . solve_part_two($binaries) . "\n";
}
}
function solve_part_one(array $binaries): int
{
$gamma = "";
$epsilon = "";
for ($i = 0; $i < strlen($binaries[0]) - 1; $i++) {
$zeroes = 0;
$ones = 0;
foreach ($binaries as $bin) {
if ((int)($bin[$i]) == 0)
$zeroes += 1;
else
$ones += 1;
}
if ($zeroes > $ones) {
$gamma .= "0";
$epsilon .= "1";
} else {
$gamma .= "1";
$epsilon .= "0";
}
}
return bindec($gamma) * bindec($epsilon);
}
function solve_part_two(array $binaries): int
{
$o2 = "";
$co2 = "";
$possible_o2 = $binaries;
$possible_co2 = $binaries;
for ($i = 0; $i < strlen($possible_o2[0]); $i++) {
$zeroes = 0;
$ones = 0;
foreach ($possible_o2 as $bin) {
if ((int)($bin[$i]) == 0)
$zeroes += 1;
else
$ones += 1;
}
if ($zeroes > $ones)
$mcb = "0";
elseif ($ones > $zeroes)
$mcb = "1";
else
$mcb = "=";
$new_o2 = [];
foreach ($possible_o2 as $binary) {
if ($o2 == "") {
if ($mcb == "0" && $binary[$i] == "0")
$new_o2[] = $binary;
elseif (($mcb == "1" || $mcb == "=") && $binary[$i] == "1")
$new_o2[] = $binary;
}
}
if (count($new_o2) == 1)
$o2 = $new_o2[0];
else
$possible_o2 = $new_o2;
if ($o2 != "")
break;
}
for ($i = 0; $i < strlen($possible_co2[0]); $i++) {
$zeroes = 0;
$ones = 0;
foreach ($possible_co2 as $bin) {
if ((int)($bin[$i]) == 0)
$zeroes += 1;
else
$ones += 1;
}
if ($zeroes > $ones)
$mcb = "0";
elseif ($ones > $zeroes)
$mcb = "1";
else
$mcb = "=";
$new_co2 = [];
foreach ($possible_co2 as $binary) {
if ($co2 == "") {
if (($mcb == "1" || $mcb == "=") && $binary[$i] == "0")
$new_co2[] = $binary;
elseif ($mcb == "0" && $binary[$i] == "1")
$new_co2[] = $binary;
}
}
if (count($new_co2) == 1)
$co2 = $new_co2[0];
else
$possible_co2 = $new_co2;
if ($co2 != "")
break;
}
return bindec($o2) * bindec($co2);
}