Files
advent-of-code-2023/day01/Part2.hs

40 lines
1.8 KiB
Haskell

module Part2 where
import Commons
import Data.Char (isDigit)
import Data.List (isPrefixOf)
getCalibrationValueLeft :: CalibrationLine -> Char
getCalibrationValueLeft line | "one" `isPrefixOf` line = '1'
| "two" `isPrefixOf` line = '2'
| "three" `isPrefixOf` line = '3'
| "four" `isPrefixOf` line = '4'
| "five" `isPrefixOf` line = '5'
| "six" `isPrefixOf` line = '6'
| "seven" `isPrefixOf` line = '7'
| "eight" `isPrefixOf` line = '8'
| "nine" `isPrefixOf` line = '9'
getCalibrationValueLeft (h: _) | isDigit h = h
getCalibrationValueLeft (_: t) = getCalibrationValueLeft t
getCalibrationValueRight :: CalibrationLine -> Char
getCalibrationValueRight line | "eno" `isPrefixOf` line = '1'
| "owt" `isPrefixOf` line = '2'
| "eerht" `isPrefixOf` line = '3'
| "ruof" `isPrefixOf` line = '4'
| "evif" `isPrefixOf` line = '5'
| "xis" `isPrefixOf` line = '6'
| "neves" `isPrefixOf` line = '7'
| "thgie" `isPrefixOf` line = '8'
| "enin" `isPrefixOf` line = '9'
getCalibrationValueRight (h: _) | isDigit h = h
getCalibrationValueRight (_: t) = getCalibrationValueRight t
getCalibrationValue :: CalibrationLine -> Integer
getCalibrationValue line = read [getCalibrationValueLeft line, getCalibrationValueRight (reverse line)]
getCalibrationValues :: CalibrationDocument -> [Integer]
getCalibrationValues [h] = [getCalibrationValue h]
getCalibrationValues (h: t) = getCalibrationValue h: getCalibrationValues t