This commit is contained in:
2023-12-02 12:45:15 +01:00
parent 787691d640
commit b167933285
4 changed files with 87 additions and 0 deletions

41
day02/Commons.hs Normal file
View File

@@ -0,0 +1,41 @@
module Commons where
import Data.String.Utils
import System.IO
import Text.Read
data Round = Round { red :: Int, green :: Int, blue :: Int }
data Game = Game { gid :: Int, rounds :: [Round] }
parseCubes :: [String] -> Round -> Round
parseCubes [] round = round
parseCubes ((h: ' ': 'r': 'e': 'd': []): t) round = parseCubes t round {red = read [h]}
parseCubes ((h1: h2: ' ': 'r': 'e': 'd': []): t) round = parseCubes t round {red = read [h1, h2]}
parseCubes ((h: ' ': 'g': 'r': 'e': 'e': 'n': []): t) round = parseCubes t round {green = read [h]}
parseCubes ((h1: h2: ' ': 'g': 'r': 'e': 'e': 'n': []): t) round = parseCubes t round {green = read [h1, h2]}
parseCubes ((h: ' ': 'b': 'l': 'u': 'e': []): t) round = parseCubes t round {blue = read [h]}
parseCubes ((h1: h2: ' ': 'b': 'l': 'u': 'e': []): t) round = parseCubes t round {blue = read [h1, h2]}
parseRound :: String -> Round
parseRound roundRaw = parseCubes (split ", " roundRaw) Round {red = 0, green = 0, blue = 0}
parseRounds :: String -> [Round]
parseRounds roundsRaw = map parseRound (split "; " roundsRaw)
parseGame :: String -> Game
parseGame ('G': 'a': 'm': 'e': ' ': h: ':': ' ': t) = Game {gid = read [h], rounds = parseRounds t}
parseGame ('G': 'a': 'm': 'e': ' ': h1: h2: ':': ' ': t) = Game {gid = read [h1, h2], rounds = parseRounds t}
parseGame ('G': 'a': 'm': 'e': ' ': h1: h2: h3: ':': ' ': t) = Game {gid = read [h1, h2, h3], rounds = parseRounds t}
parseGame (_: t) = parseGame t
parse :: IO [Game]
parse = do done <- isEOF
if done
then return []
else do line <- getLine
let game = parseGame line
otherGames <- parse
return (game: otherGames)