From 9cd5b11547e2805359271703944e316cc071eb67 Mon Sep 17 00:00:00 2001 From: cos Date: Fri, 1 Dec 2023 23:58:06 +0100 Subject: Add day01, 2023 (haskell) --- 2023/haskell/day01/part1.hs | 17 +++++++++++++++++ 2023/haskell/day01/part2.hs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 2023/haskell/day01/part1.hs create mode 100644 2023/haskell/day01/part2.hs diff --git a/2023/haskell/day01/part1.hs b/2023/haskell/day01/part1.hs new file mode 100644 index 0000000..65ea098 --- /dev/null +++ b/2023/haskell/day01/part1.hs @@ -0,0 +1,17 @@ +import Data.Char +import System.Environment +import System.IO + +main :: IO () +main = do + args <- getArgs + case args of + [filename] -> do + fh <- openFile filename ReadMode + lines <- lines <$> readFile filename + let digits = map (\line -> [c | c <- line, isDigit c ]) lines + let numbers = map (\line -> head line : [last line]) digits + let ints = map (\num -> read num :: Int ) numbers + let part1 = sum ints + print part1 + _ -> putStrLn "Missing input filename." diff --git a/2023/haskell/day01/part2.hs b/2023/haskell/day01/part2.hs new file mode 100644 index 0000000..a99fabf --- /dev/null +++ b/2023/haskell/day01/part2.hs @@ -0,0 +1,31 @@ +import Data.Char +import Data.List +import System.Environment +import System.IO + +fixInput str + | "one" `isPrefixOf` str = '1' + | "two" `isPrefixOf` str = '2' + | "three" `isPrefixOf` str = '3' + | "four" `isPrefixOf` str = '4' + | "five" `isPrefixOf` str = '5' + | "six" `isPrefixOf` str = '6' + | "seven" `isPrefixOf` str = '7' + | "eight" `isPrefixOf` str = '8' + | "nine" `isPrefixOf` str = '9' + | otherwise = head str + +main :: IO () +main = do + args <- getArgs + case args of + [filename] -> do + fh <- openFile filename ReadMode + lines <- lines <$> readFile filename + let fixed = [ [ fixInput part | part <- tails line, part /= "" ] | line <- lines ] + let digits = map (\line -> [c | c <- line, isDigit c ]) fixed + let numbers = map (\line -> head line : [last line]) digits + let ints = map (\num -> read num :: Int ) numbers + let part2 = sum ints + print part2 + _ -> putStrLn "Missing input filename." -- cgit v1.2.3