advent_of_code_2021/day_8/part_2.php

100 lines
3.4 KiB
PHP
Raw Permalink Normal View History

<?php
$entries = explode("\n", file_get_contents('./input.txt'));
$outputs = [];
foreach ($entries as $entry) {
[$uniques, $output] = explode('|', $entry);
$uniques = array_filter(explode(' ', $uniques));
$output = array_filter(explode(' ', $output));
$mapping = [];
while (count($mapping) !== 10) {
foreach ($uniques as $unique) {
$unique = sort_string($unique);
if (in_array($unique, $mapping)) {
continue;
}
switch (strlen($unique)) {
case 2: $mapping[1] = $unique; break;
case 4: $mapping[4] = $unique; break;
case 3: $mapping[7] = $unique; break;
case 7: $mapping[8] = $unique; break;
case 5:
if (array_key_exists(1, $mapping)) {
$segments_1 = str_split($mapping[1]);
if (str_contains($unique, $segments_1[0]) && str_contains($unique, $segments_1[1])) {
$mapping[3] = $unique;
break;
}
}
if (array_key_exists(9, $mapping)) {
$segments_9 = str_split($mapping[9]);
$count = 0;
foreach ($segments_9 as $segment_9) {
if (!str_contains($unique, $segment_9)) {
$count++;
}
}
if ($count === 1) {
$mapping[5] = $unique;
break;
} else {
$mapping[2] = $unique;
break;
}
}
break;
case 6:
if (array_key_exists(1, $mapping)) {
$segments_1 = str_split($mapping[1]);
if (!str_contains($unique, $segments_1[0]) || !str_contains($unique, $segments_1[1])) {
$mapping[6] = $unique;
break;
}
}
if (array_key_exists(4, $mapping)) {
$segments_4 = str_split($mapping[4]);
if (
str_contains($unique, $segments_4[0]) &&
str_contains($unique, $segments_4[1]) &&
str_contains($unique, $segments_4[2]) &&
str_contains($unique, $segments_4[3])
) {
$mapping[9] = $unique;
break;
}
}
if (array_key_exists(6, $mapping) && array_key_exists(9, $mapping)) {
$mapping[0] = $unique;
break;
}
break;
default:
echo 'unknown length : '.strlen($unique);
}
}
}
$number = '';
foreach ($output as $item) {
$item = sort_string($item);
$number .= array_search($item, $mapping);
}
echo sprintf('%u%s', $number, "\n");
$outputs[] = (int) $number;
}
echo array_sum($outputs);
function sort_string(string $string)
{
$string = str_split($string);
sort($string);
return implode($string);
}