2021-12-09 22:41:22 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace trizz\AdventOfCode\Y21;
|
|
|
|
|
|
|
|
use trizz\AdventOfCode\Solution;
|
|
|
|
|
2022-11-29 19:52:02 +01:00
|
|
|
final class Day3 extends Solution
|
2021-12-09 22:41:22 +01:00
|
|
|
{
|
|
|
|
public static int|string|null $part1ExampleResult = 198;
|
2022-11-29 19:52:02 +01:00
|
|
|
|
|
|
|
public static int|string|null $part1Result = 3_309_596;
|
2021-12-09 22:41:22 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function part1(array $data): int
|
|
|
|
{
|
|
|
|
$bits = [];
|
|
|
|
|
|
|
|
foreach ($data as $binary) {
|
|
|
|
$split = str_split($binary);
|
|
|
|
|
|
|
|
foreach ($split as $position => $value) {
|
|
|
|
$bits[$position][] = $value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
$gammaRate = '';
|
|
|
|
$epsilonRate = '';
|
|
|
|
|
2022-11-29 19:52:02 +01:00
|
|
|
foreach ($bits as $bit) {
|
|
|
|
$zeros = array_filter($bit, static fn ($value) => $value === '0');
|
|
|
|
$ones = array_filter($bit, static fn ($value) => $value === '1');
|
2021-12-09 22:41:22 +01:00
|
|
|
|
|
|
|
$gammaRate .= ($ones > $zeros) ? '1' : '0';
|
|
|
|
$epsilonRate .= ($ones < $zeros) ? '1' : '0';
|
|
|
|
}
|
|
|
|
|
|
|
|
return (int) (bindec($gammaRate) * bindec($epsilonRate));
|
|
|
|
}
|
|
|
|
}
|