[2017-12-06] Solutions for both puzzles
parent
0e6234f2f7
commit
6b107a2661
2
Makefile
2
Makefile
|
@ -16,6 +16,8 @@ day5:
|
|||
php day5/main.php
|
||||
|
||||
day6:
|
||||
php day6/main.php
|
||||
|
||||
day7:
|
||||
day8:
|
||||
day9:
|
||||
|
|
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue