Skip to content

Instantly share code, notes, and snippets.

@Dierk
Last active December 8, 2017 09:18
Show Gist options
  • Save Dierk/01cb60beec8941b35a04a86fab985ca2 to your computer and use it in GitHub Desktop.
Save Dierk/01cb60beec8941b35a04a86fab985ca2 to your computer and use it in GitHub Desktop.
Advent of Frege code, day 6
module Advent6 where
{-
http://adventofcode.com/2017/day/6
-}
import Data.List
mapAtIndex :: (a->a) -> Int -> [a] -> [a]
mapAtIndex f n xs = take n xs ++ rest (drop n xs) where
rest (y:ys) = f y : ys
rest [] = [] -- index is outside: no mapping
incAtIndex = mapAtIndex (+1)
setAtIndex x = mapAtIndex (const x)
startBank = [4,1,15,12,0,9,9,5,5,8,7,3,14,5,12,3]
distribute soMany fromIdx xs
| soMany == 0 ->
xs
| fromIdx >= length xs ->
distribute soMany 0 xs
| otherwise ->
distribute (soMany-1) (fromIdx+1) (incAtIndex fromIdx xs)
allBanks start = iterate step start where
step bank =
let maxVal = maximum bank
maxPos = unJust $ findIndex (== maxVal) bank
in distribute maxVal maxPos (setAtIndex 0 maxPos bank)
banks = allBanks startBank
idxBanks = zip [0..] banks
duplFound (untilIdx, bank) = elem bank (take untilIdx banks)
sndDuplIdx = length $ takeUntil duplFound idxBanks
main = do
println $ "Number of distribution cycles: " ++ show sndDuplIdx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment