Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Created December 1, 2023 21:45
Show Gist options
  • Save Alwinfy/2729b3536cf7d566209bf18c282756b3 to your computer and use it in GitHub Desktop.
Save Alwinfy/2729b3536cf7d566209bf18c282756b3 to your computer and use it in GitHub Desktop.
import Control.Applicative ((<|>), Alternative)
import Control.Arrow ((&&&))
import Control.Monad (guard)
import Data.Bifunctor (bimap)
import Data.Char (digitToInt, isDigit)
import Data.List (findIndex, tails, isPrefixOf)
import Data.Maybe (catMaybes, listToMaybe)
parse :: Alternative f => Char -> f Int
parse s = guard (isDigit s) *> pure (digitToInt s)
numbers :: [String]
numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
parse2 :: String -> Maybe Int
parse2 t = (listToMaybe t >>= parse) <|> (1+) <$> findIndex (`isPrefixOf` t) numbers
main :: IO ()
main = ((bimap >>= id) (sum . map (extract . catMaybes)) . (map (map parse) &&& map (map parse2 . tails)) . lines <$> getContents) >>= print
where extract ls = 10 * head ls + last ls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment