aoc2023

advent of code 2023
Log | Files | Refs | Feed | README

day1.hs (1528B)


      1 -- AOC 2023: Day 1
      2 -- Given a list of newline separated strings containing ASCII digits
      3 -- interspersed among other characters take the first and last ASCII
      4 -- digit from each line as a 2 digit number then sum all of them together
      5 -- 
      6 -- Example (Part 1):
      7 -- treb7uchet -> 77
      8 -- 1abc2 -> 12
      9 -- (Output) 89
     10 --
     11 -- Part 2: English names are also intersperced with the digits and
     12 -- are also valid for making up the first and last digits.
     13 --
     14 -- Example (Part 2):
     15 -- 4nineeightseven2 -> 42
     16 -- zoneight234 -> 14
     17 -- (Output) 56
     18 --
     19 {-# LANGUAGE OverloadedStrings #-}
     20 
     21 import Data.Char
     22 import qualified Data.Text as T
     23 import qualified Data.Text.IO as TI
     24 
     25 stripalpha :: T.Text -> T.Text
     26 stripalpha = T.filter (`elem` ['0' .. '9'])
     27 
     28 tocode :: T.Text -> Int
     29 tocode st =
     30     let h = T.head st
     31         t = T.last st
     32         z = ord '0'
     33      in 10 * (ord h - z) + (ord t - z)
     34 
     35 replmap :: (T.Text, T.Text) -> (T.Text -> T.Text)
     36 replmap (f, s) = T.replace f s
     37 
     38 repstrnums :: T.Text -> T.Text
     39 repstrnums =
     40     let pairs =
     41             [ ("one", "o1e")
     42             , ("two", "t2o")
     43             , ("three", "t3e")
     44             , ("four", "4")
     45             , ("five", "5e")
     46             , ("six", "6")
     47             , ("seven", "7n")
     48             , ("eight", "e8t")
     49             , ("nine", "n9e")
     50             ]
     51      in foldr1 (.) $ map replmap pairs
     52 
     53 getcal :: [T.Text] -> [Int]
     54 getcal = map $ tocode . stripalpha
     55 
     56 main = do
     57     contents <- TI.getContents
     58     print $ sum $ getcal $ T.lines contents
     59     print $ sum $ getcal $ T.lines $ repstrnums contents