aoc2022/20-a.hs

42 lines
1.1 KiB
Haskell

import Common
import Data.List (elemIndex, intercalate)
import Data.Maybe (fromJust)
wrap :: Int -> Int -> Int
wrap length index
| index == 0 = length - 1
| index >= length = wrap length $ index - length + 1
| index < 0 = wrap length $ index + length - 1
| otherwise = index
coordinates = [1000, 2000, 3000]
decrypt :: [Int] -> Int
decrypt a = sum $ map test coordinates
where
test n = mixed !! (zeroIndex + n)
zeroIndex = fromJust $ elemIndex 0 mixed
mixed = cycle $ fst $ foldl step (a, indices) indices
indices = [0 .. len - 1]
len = length a
step :: ([Int], [Int]) -> Int -> ([Int], [Int])
step (values, indices) i = (mix values index value, mix indices index value)
where
value = values !! index
index = fromJust $ elemIndex i indices
mix :: [Int] -> Int -> Int -> [Int]
mix list i x = newList
where
newList = listStart ++ value : listEnd
(listStart, listEnd) = splitAt newIndex list'
newIndex = wrap len $ i + x
list' = (\(l, r) -> l ++ tail r) $ splitAt i list
value = list !! i
main = interact $
show
. decrypt
. map read . lines