module Part2 where import Commons import Data.Array (Array, array, (!), (//), assocs, listArray) type Hashmap = Array Int [Instruction] initHashmap :: Hashmap initHashmap = listArray (0, 255) [[] | _ <- [0..255]] applyInstructionToList :: [Instruction] -> Instruction -> [Instruction] applyInstructionToList [] i | iType i == Set = [i] | otherwise = [] applyInstructionToList (h: t) i | iType i == Set && label h == label i = i: t | iType i == Remove && label h == label i = t | otherwise = h: applyInstructionToList t i applyInstruction :: Hashmap -> Instruction -> Hashmap applyInstruction m i = let hash = getHash 0 (label i) in m // [(hash, applyInstructionToList (m ! hash) i)] applyInstructions :: [Instruction] -> Hashmap applyInstructions = foldl applyInstruction initHashmap getFocusingPowerFromList :: Int -> Int -> [Instruction] -> [Int] getFocusingPowerFromList _ _ [] = [] getFocusingPowerFromList i slot (h: t) = i * slot * focal h: getFocusingPowerFromList i (slot + 1) t getFocusingPower :: Hashmap -> [Int] getFocusingPower = concatMap (\ (i, h) -> getFocusingPowerFromList (i + 1) 1 h) . assocs getAllFocusingPower :: [Instruction] -> [Int] getAllFocusingPower = getFocusingPower . applyInstructions