Skip to content

Instantly share code, notes, and snippets.

@zypeh
Created May 27, 2024 19:54
Show Gist options
  • Save zypeh/1ee4900ab77615044a806a0d14e423fc to your computer and use it in GitHub Desktop.
Save zypeh/1ee4900ab77615044a806a0d14e423fc to your computer and use it in GitHub Desktop.
module Main where
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BSC
import Data.Char (isDigit)
main :: IO ()
main = do
content <- BS.readFile "input.txt"
let lines_sep = BSC.lines content
let x = fmap (take_first_and_last . filter isDigit) (BSC.unpack <$> lines_sep)
print $ sum x
take_first_and_last :: [Char] -> Int
take_first_and_last [] = error "no number in this line"
take_first_and_last (x : []) = read (x : [x])
take_first_and_last (x : xs) = let l = last xs in read (x : [l])
module Main where
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BSC
import Data.Char (isDigit)
import Data.List (tails)
main :: IO ()
main = do
content <- BS.readFile "input.txt"
let lines_sep = BSC.lines content
let x = fmap (process [] . concat . windows 5) (BSC.unpack <$> lines_sep)
print $ sum x
windows :: Int -> [a] -> [[a]]
windows n = fmap (take n) . tails
process :: [Char] -> [Char] -> Int
process x ('o' : 'n' : 'e' : xs) = process (x ++ ['1']) xs
process x ('t' : 'w' : 'o' : xs) = process (x ++ ['2']) xs
process x ('t' : 'h' : 'r' : 'e' : 'e' : xs) = process (x ++ ['3']) xs
process x ('f' : 'o' : 'u' : 'r' : xs) = process (x ++ ['4']) xs
process x ('f' : 'i' : 'v' : 'e' : xs) = process (x ++ ['5']) xs
process x ('s' : 'i' : 'x' : xs) = process (x ++ ['6']) xs
process x ('s' : 'e' : 'v' : 'e' : 'n' : xs) = process (x ++ ['7']) xs
process x ('e' : 'i' : 'g' : 'h' : 't' : xs) = process (x ++ ['8']) xs
process x ('n' : 'i' : 'n' : 'e' : xs) = process (x ++ ['9']) xs
process x (i : xs) =
if isDigit i
then process (x ++ [i]) xs
else process x xs
process bucket [] = take_first_and_last bucket
where
take_first_and_last :: [Char] -> Int
take_first_and_last [] = error $ "no number in this line"
take_first_and_last (x : []) = read (x : [x])
take_first_and_last (x : xs) = let l = last xs in read (x : [l])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment