2023 day 1 in Haskell
This commit is contained in:
parent
ac432067c5
commit
8bf8581dc3
|
@ -0,0 +1,43 @@
|
|||
import Data.Char (digitToInt, isDigit)
|
||||
import Data.List (isPrefixOf, tails)
|
||||
import Text.Printf (printf)
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
input <- lines <$> getContents
|
||||
putStr $ printf "Part 1: %d\n" (part1 input)
|
||||
putStr $ printf "Part 2: %d\n" (part2 input)
|
||||
|
||||
part1 :: [String] -> Int
|
||||
part1 = solution getDigits
|
||||
|
||||
part2 :: [String] -> Int
|
||||
part2 = solution getDigits'
|
||||
|
||||
solution :: (String -> [Int]) -> [String] -> Int
|
||||
solution f = sum . map (digitsToNumber . f)
|
||||
|
||||
getDigits :: [Char] -> [Int]
|
||||
getDigits = map digitToInt . filter isDigit
|
||||
|
||||
digitsToNumber :: [Int] -> Int
|
||||
digitsToNumber [] = 0
|
||||
digitsToNumber xs = head xs * 10 + last xs
|
||||
|
||||
getDigits' :: String -> [Int]
|
||||
getDigits' = foldMap digitAtPosition . tails
|
||||
|
||||
digitAtPosition :: String -> [Int]
|
||||
digitAtPosition x
|
||||
| withPrefix "1" || withPrefix "one" = [1]
|
||||
| withPrefix "2" || withPrefix "two" = [2]
|
||||
| withPrefix "3" || withPrefix "three" = [3]
|
||||
| withPrefix "4" || withPrefix "four" = [4]
|
||||
| withPrefix "5" || withPrefix "five" = [5]
|
||||
| withPrefix "6" || withPrefix "six" = [6]
|
||||
| withPrefix "7" || withPrefix "seven" = [7]
|
||||
| withPrefix "8" || withPrefix "eight" = [8]
|
||||
| withPrefix "9" || withPrefix "nine" = [9]
|
||||
| otherwise = []
|
||||
where
|
||||
withPrefix p = p `isPrefixOf` x
|
Loading…
Reference in New Issue