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

35
day15/Part2.hs Normal file
View File

@@ -0,0 +1,35 @@
module Part2 where
import Commons
import GHC.Arr (Array(Array), array, (!), (//), assocs)
type Hashmap = Array Int [Instruction]
initHashmap :: Hashmap
initHashmap = array (0, 255) [(i, []) | i <- [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 (label i ) 0
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 m = concatMap (\ (i, h) -> getFocusingPowerFromList (i + 1) 1 h) (assocs m)
getAllFocusingPower :: [Instruction] -> [Int]
getAllFocusingPower = getFocusingPower . applyInstructions