diff --git a/Makefile b/Makefile index 3bc71c2..270dca7 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,8 @@ day5: php day5/main.php day6: + php day6/main.php + day7: day8: day9: diff --git a/day6/main.php b/day6/main.php new file mode 100644 index 0000000..5b8b83b --- /dev/null +++ b/day6/main.php @@ -0,0 +1,93 @@ + 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; +}