day03: Solve puzzles

main
Elis Hirwing 10 months ago
parent 4877103ed9
commit d56a9fb9b2
Signed by: etu
GPG Key ID: D57EFA625C9A925F
  1. 2
      Makefile
  2. 12
      day03/example.txt
  3. 1000
      day03/input.txt
  4. 70
      day03/solve.php

@ -9,6 +9,8 @@ day02:
php day02/solve.php input
day03:
php day03/solve.php input
day04:
day05:
day06:

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010

File diff suppressed because it is too large Load Diff

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
require_once(__DIR__.'/../lib/functions.php');
$entries = getLines(__DIR__.'/'.$argv[1].'.txt');
timedPrintf(
'[2021-12-03.1] Resulting power consumption: %d [Time: %ss]',
(function (array $entries) : int {
// Fill array with zeroes
$counters = array_fill(0, strlen($entries[0]), 0);
foreach ($entries as $entry) {
for ($i = 0; $i < strlen($entry); $i++) {
if ($entry[$i] === '1') {
$counters[$i] += 1;
}
}
}
$gamma = '';
$epsilon = '';
foreach ($counters as $counter) {
$gamma .= ($counter > (count($entries) / 2)) ? '1' : '0';
$epsilon .= ($counter > (count($entries) / 2)) ? '0' : '1';
}
return bindec($gamma) * bindec($epsilon);
}),
$entries
);
timedPrintf(
'[2021-12-03.2] Resulting life support rating: %d [Time: %ss]',
(function (array $entries) : int {
$fn = function (array $numbers, int $column, bool $filterByMore, callable $fn) : int {
$counter = 0;
foreach ($numbers as $number) {
if ($number[$column] === '1') {
$counter++;
}
}
$filterByNumber = $filterByMore ?
(($counter >= (count($numbers) / 2)) ? '1' : '0') :
(($counter < (count($numbers) / 2)) ? '1' : '0');
// Filter the array
$numbers = array_filter($numbers, function (string $number) use ($column, $filterByNumber) : bool {
return $number[$column] === $filterByNumber;
});
// If only one number left, decode it from binary and return it
if (count($numbers) === 1) {
return bindec(array_shift($numbers));
}
// Otherwise, recurse more
return $fn($numbers, $column + 1, $filterByMore, $fn);
};
$o2generator = $fn($entries, 0, true, $fn);
$co2 = $fn($entries, 0, false, $fn);
return $o2generator * $co2;
}),
$entries
);
Loading…
Cancel
Save