Files
advent-of-code-2023/day03/Part2.hs
2023-12-04 19:05:20 +01:00

36 lines
1.5 KiB
Haskell

module Part2 where
import Commons
getNumberNeighbors :: Coordinates -> [NumberPart] -> Int
getNumberNeighbors _ [] = 0
getNumberNeighbors symbolCoordinates (h: t)
| symbolCoordinates `elem` neighbors h = 1 + getNumberNeighbors symbolCoordinates t
| otherwise = getNumberNeighbors symbolCoordinates t
isGear :: SymbolPart -> [NumberPart] -> Bool
isGear symbolPart numberParts | symbol symbolPart == '*' = getNumberNeighbors (coordinates symbolPart) numberParts == 2
| otherwise = False
getRatioNeighbors :: Coordinates -> [NumberPart] -> Int
getRatioNeighbors _ [] = 1
getRatioNeighbors symbolCoordinates (h: t)
| symbolCoordinates `elem` neighbors h = value h * getRatioNeighbors symbolCoordinates t
| otherwise = getRatioNeighbors symbolCoordinates t
getGearRatio :: SymbolPart -> [NumberPart] -> Int
getGearRatio symbolPart numberParts
| isGear symbolPart numberParts = getRatioNeighbors (coordinates symbolPart) numberParts
| otherwise = 0
getGearRatios :: [SymbolPart] -> [NumberPart] -> [Int]
getGearRatios [] _ = []
getGearRatios (h: t) numberParts = let gearRatio = getGearRatio h numberParts
in if gearRatio > 0
then gearRatio: getGearRatios t numberParts
else getGearRatios t numberParts
getGearRatiosFromEngine :: Engine -> [Int]
getGearRatiosFromEngine engine = getGearRatios (symbols engine) $ numbers engine