8th day both parts
This commit is contained in:
51
08/part2.php
Normal file
51
08/part2.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
$input = array_map(fn($line) => explode(' | ', $line), $input);
|
||||
$sum = 0;
|
||||
foreach ($input as $digits) {
|
||||
$sum += decodeNumbers(explode(' ', $digits[0]), explode(' ', $digits[1]));
|
||||
}
|
||||
echo $sum; //961734
|
||||
|
||||
function decodeNumbers($inputArray, $displayedNumbers)
|
||||
{
|
||||
foreach ($inputArray as &$digits) {
|
||||
$digits = str_split($digits);
|
||||
sort($digits);
|
||||
}
|
||||
|
||||
foreach ($displayedNumbers as &$displayedNumber) {
|
||||
$displayedNumber = str_split($displayedNumber);
|
||||
sort($displayedNumber);
|
||||
}
|
||||
|
||||
$numbers = array_fill(0, 9, null);
|
||||
|
||||
$numbers[1] = current(array_filter($inputArray, fn($element) => count($element) == 2));
|
||||
unset($inputArray[array_search($numbers[1], $inputArray)]);
|
||||
$numbers[4] = current(array_filter($inputArray, fn($element) => count($element) == 4));
|
||||
unset($inputArray[array_search($numbers[4], $inputArray)]);
|
||||
$numbers[7] = current(array_filter($inputArray, fn($element) => count($element) == 3));
|
||||
unset($inputArray[array_search($numbers[7], $inputArray)]);
|
||||
$numbers[8] = current(array_filter($inputArray, fn($element) => count($element) == 7));
|
||||
unset($inputArray[array_search($numbers[8], $inputArray)]);
|
||||
$numbers[9] = current(array_filter($inputArray, fn($element) => count($element) == 6 && count(array_diff($element, $numbers[4])) == 2));
|
||||
unset($inputArray[array_search($numbers[9], $inputArray)]);
|
||||
$numbers[0] = current(array_filter($inputArray, fn($element) => count($element) == 6 && count(array_diff($element, $numbers[1])) == 4));
|
||||
unset($inputArray[array_search($numbers[0], $inputArray)]);
|
||||
$numbers[6] = current(array_filter($inputArray, fn($element) => count($element) == 6));
|
||||
unset($inputArray[array_search($numbers[6], $inputArray)]);
|
||||
$numbers[5] = current(array_filter($inputArray, fn($element) => count($element) == 5 && count(array_diff($numbers[6], $element)) == 1));
|
||||
unset($inputArray[array_search($numbers[5], $inputArray)]);
|
||||
$numbers[2] = current(array_filter($inputArray, fn($element) => count($element) == 5 && count(array_diff($numbers[5], $element)) == 2));
|
||||
unset($inputArray[array_search($numbers[2], $inputArray)]);
|
||||
$numbers[3] = current(array_filter($inputArray, fn($element) => count($element) == 5));
|
||||
unset($inputArray[array_search($numbers[3], $inputArray)]);
|
||||
|
||||
$result = '';
|
||||
foreach ($displayedNumbers as $number) {
|
||||
$result .= array_search($number, $numbers);
|
||||
}
|
||||
return (int)$result;
|
||||
}
|
||||
Reference in New Issue
Block a user