aoc2022/20-a.hs

42 lines
1.1 KiB
Haskell
Raw Permalink Normal View History

2022-12-21 20:03:05 +01:00
import Common
2022-12-22 01:35:01 +01:00
import Data.List (elemIndex, intercalate)
2022-12-21 20:03:05 +01:00
import Data.Maybe (fromJust)
wrap :: Int -> Int -> Int
wrap length index
| index == 0 = length - 1
2022-12-22 01:35:01 +01:00
| index >= length = wrap length $ index - length + 1
| index < 0 = wrap length $ index + length - 1
2022-12-21 20:03:05 +01:00
| 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
2022-12-22 01:35:01 +01:00
mixed = cycle $ fst $ foldl step (a, indices) indices
2022-12-21 20:03:05 +01:00
2022-12-22 01:35:01 +01:00
indices = [0 .. len - 1]
2022-12-21 20:03:05 +01:00
len = length a
2022-12-22 01:35:01 +01:00
step :: ([Int], [Int]) -> Int -> ([Int], [Int])
step (values, indices) i = (mix values index value, mix indices index value)
2022-12-21 20:03:05 +01:00
where
2022-12-22 01:35:01 +01:00
value = values !! index
index = fromJust $ elemIndex i indices
mix :: [Int] -> Int -> Int -> [Int]
mix list i x = newList
where
newList = listStart ++ value : listEnd
2022-12-21 20:03:05 +01:00
(listStart, listEnd) = splitAt newIndex list'
2022-12-22 01:35:01 +01:00
newIndex = wrap len $ i + x
list' = (\(l, r) -> l ++ tail r) $ splitAt i list
value = list !! i
2022-12-21 20:03:05 +01:00
main = interact $
show
. decrypt
. map read . lines