diff options
author | tomsmeding <tom.smeding@gmail.com> | 2017-12-06 20:10:28 +0100 |
---|---|---|
committer | tomsmeding <tom.smeding@gmail.com> | 2017-12-06 20:10:28 +0100 |
commit | 91e701168e87ff2a998a17151ce3cf0c4e35c385 (patch) | |
tree | 0ed960bc8f161c97d8f191684af7e864afb198a7 /2017 | |
parent | efaded6a41b4c254334f37bd77c8ed0765a1fa49 (diff) |
Day 6
Diffstat (limited to '2017')
-rw-r--r-- | 2017/6.hs | 32 | ||||
-rw-r--r-- | 2017/6.in | 1 |
2 files changed, 33 insertions, 0 deletions
diff --git a/2017/6.hs b/2017/6.hs new file mode 100644 index 0000000..d4390ab --- /dev/null +++ b/2017/6.hs @@ -0,0 +1,32 @@ +import Control.Monad +import Data.List +import qualified Data.Map.Strict as Map + + +modifyAt :: Show a => Int -> (a -> a) -> [a] -> [a] +modifyAt i f l = + let (pre, v : post) = splitAt i l + in pre ++ f v : post + +redistribute :: [Int] -> [Int] +redistribute blocks = + let Just idx = findIndex (== maximum blocks) blocks + amt = blocks !! idx + len = length blocks + spread _ 0 b = b + spread i a b = spread (succ i `mod` len) (pred a) (modifyAt i succ b) + in spread (succ idx `mod` len) amt (modifyAt idx (const 0) blocks) + +cycledetect :: [Int] -> (Int, Int) +cycledetect blocks = go Map.empty 0 blocks + where + go mp idx bl = case Map.lookup bl mp of + Nothing -> go (Map.insert bl idx mp) (succ idx) (redistribute bl) + Just i -> (idx, idx - i) + +main :: IO () +main = do + blocks <- liftM (map read . words) (readFile "6.in") + let (q1, q2) = cycledetect blocks + print q1 + print q2 diff --git a/2017/6.in b/2017/6.in new file mode 100644 index 0000000..d369702 --- /dev/null +++ b/2017/6.in @@ -0,0 +1 @@ +2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14 |