This commit is contained in:
2023-12-15 12:21:40 +01:00
parent 8614db903e
commit 20d249b715
5 changed files with 87 additions and 0 deletions

35
day15/Part2.hs Normal file
View File

@@ -0,0 +1,35 @@
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