[2017-12-06] Solutions for both puzzles

master
Elis Hirwing 2017-12-06 07:48:43 +01:00
parent 0e6234f2f7
commit 6b107a2661
Signed by: etu
GPG Key ID: D57EFA625C9A925F
2 changed files with 95 additions and 0 deletions

View File

@ -16,6 +16,8 @@ day5:
php day5/main.php
day6:
php day6/main.php
day7:
day8:
day9:

93
day6/main.php Normal file
View File

@ -0,0 +1,93 @@
<?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;
}