X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=adventofcode1701%2Fapp%2Fadvent01.hs;h=d56fdbddb365eab2418796fb14ac978b6504f06d;hb=765da598a39a2c2b93102c182272b5546f4b6996;hp=dc63f9cccb7371cfd927dbac08bbe4cbf36ef6df;hpb=931b8f4140207d95611a9904407226c034713cbd;p=advent-of-code-17.git diff --git a/adventofcode1701/app/advent01.hs b/adventofcode1701/app/advent01.hs index dc63f9c..d56fdbd 100644 --- a/adventofcode1701/app/advent01.hs +++ b/adventofcode1701/app/advent01.hs @@ -2,41 +2,30 @@ module Main(main) where -import Text.Parsec hiding (State) --- import Text.ParserCombinators.Parsec.Number - - +import Data.List (tails) main :: IO () main = do - text <- readFile "data/advent01.txt" - let instructions = successfulParse $ parseIline text - part1 instructions - part2 instructions - -part1 :: [Int] -> IO () -part1 instructions = do - print $ sum instructions - -part2 :: [Int] -> IO () -part2 instructions = do - print $ length $ takeWhile (>= 0) $ scanl (+) 0 instructions - - - --- instructionFile = instructionLine `endBy` newline -instructionLine = many (up <|> down) + digits <- readFile "data/advent01.txt" + print $ part1 digits + print $ part2 digits +part1 :: String -> Integer +part1 = sum_valid_pairs . part1_extract -up = char '(' *> pure 1 -down = char ')' *> pure -1 +part2 :: String -> Integer +part2 = sum_valid_pairs . part2_extract --- parseIfile :: String -> Either ParseError [[Int]] --- parseIfile input = parse instructionFile "(unknown)" input +part1_extract :: String -> [String] +part1_extract digits = map (take 2) $ tails (digits ++ [head digits]) -parseIline :: String -> Either ParseError [Int] -parseIline input = parse instructionLine "(unknown)" input +part2_extract :: String -> [String] +part2_extract digits = map (\ds -> (take 1 ds) ++ (take 1 $ drop offset ds)) + $ take (length digits) + $ tails (digits ++ digits) + where offset = length digits `div` 2 -successfulParse :: Either ParseError [a] -> [a] -successfulParse (Left _) = [] -successfulParse (Right a) = a +sum_valid_pairs :: [String] -> Integer +sum_valid_pairs possibles = sum $ map (read . take 1) + $ filter (\(x:y:_) -> x == y) + $ filter (\p -> length p == 2) possibles \ No newline at end of file