You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.3 KiB
PHP

<?php
// https://adventofcode.com/2017/day/6
function puzzle1(string $input) : int
{
$history = [];
$banks = explode("\t", $input);
$sum = 0;
while (true) {
// Copy banks, sort it, get biggest number out
$copy = $banks;
rsort($copy);
$biggestNumber = array_shift($copy);
// Find the key and value to distribute
$distributeKey = array_search($biggestNumber, $banks);
$distributeValue = $banks[$distributeKey];
$banks[$distributeKey] = 0;
while ($distributeValue > 0) {
$distributeKey++;
if ($distributeKey > count($banks) - 1) {
$distributeKey = 0;
}
$banks[$distributeKey]++;
$distributeValue--;
}
// Increment reallocations
$sum++;
// Check history if we had this state before
$index = implode($banks, '');
if (isset($history[$index])) {
break;
}
$history[$index] = true;
}
return $sum;
}
function puzzle2(string $input) : int
{
$history = [];
$banks = explode("\t", $input);
$sum = 0;
while (true) {
// Copy banks, sort it, get biggest number out
$copy = $banks;
rsort($copy);
$biggestNumber = array_shift($copy);
// Find the key and value to distribute
$distributeKey = array_search($biggestNumber, $banks);
$distributeValue = $banks[$distributeKey];
$banks[$distributeKey] = 0;
while ($distributeValue > 0) {
$distributeKey++;
if ($distributeKey > count($banks) - 1) {
$distributeKey = 0;
}
$banks[$distributeKey]++;
$distributeValue--;
}
// Increment reallocations
$sum++;
// Check history if we had this state before
$index = implode($banks, '');
if (isset($history[$index])) {
$sum = $sum - $history[$index];
break;
}
$history[$index] = $sum;
}
return $sum;
}
echo 'First challange solution:'.PHP_EOL;
echo puzzle1(trim(file_get_contents(dirname(__FILE__).'/input.txt'))).PHP_EOL;
echo 'Second challange solution:'.PHP_EOL;
echo puzzle2(trim(file_get_contents(dirname(__FILE__).'/input.txt'))).PHP_EOL;