64 lines
1.7 KiB
PHP
64 lines
1.7 KiB
PHP
<?php
|
|
|
|
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
|
|
$numbers = explode(',', array_shift($input));
|
|
$input = array_map(fn($line) => explode(' ', str_replace(' ', ' ', trim($line))), $input);
|
|
$cards = array_chunk($input, 5);
|
|
$lastNumber = $lastCard = false;
|
|
foreach ($numbers as $numberIndex => $number) {
|
|
$cards = checkNumber($cards, $number);
|
|
while (($cardId = isWinner($cards)) !== false) {
|
|
$lastCard = $cards[$cardId];
|
|
$lastNumber = $number;
|
|
unset($cards[$cardId]);
|
|
}
|
|
}
|
|
echo calculateScore($lastCard, $lastNumber); //23670
|
|
|
|
var_dump($lastCard);
|
|
var_dump($cardId);
|
|
var_dump(count($cards));
|
|
|
|
function calculateScore($card, $number)
|
|
{
|
|
echo array_sum(array_map('array_sum', $card)) * $number;
|
|
}
|
|
|
|
function isWinner($cards)
|
|
{
|
|
foreach ($cards as $cardIndex => $card) {
|
|
foreach ($card as $rowId => $cardRow) {
|
|
if (array_sum(array_column($card, $rowId)) === 0) {
|
|
return $cardIndex;
|
|
}
|
|
if (array_sum($cardRow) === 0) {
|
|
return $cardIndex;
|
|
}
|
|
}
|
|
$diagonal1 = $diagonal2 = false;
|
|
for ($i = 0; $i < 5; $i++) {
|
|
$diagonal1 += (int)$card[$i][$i];
|
|
$diagonal2 += (int)$card[$i][4 - $i];
|
|
}
|
|
if ($diagonal1 === 0) {
|
|
return $cardIndex;
|
|
}
|
|
if ($diagonal2 === 0) {
|
|
return $cardIndex;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function checkNumber($cards, $number)
|
|
{
|
|
foreach ($cards as $cardIndex => $card) {
|
|
foreach ($card as $rowId => $cardRow) {
|
|
if (($index = array_search($number, $cardRow)) !== false) {
|
|
$cards[$cardIndex][$rowId][$index] = '';
|
|
}
|
|
}
|
|
}
|
|
return $cards;
|
|
} |