Another approach to day 1
[advent-of-code-17.git] / adventofcode1701 / app / advent01.hs
index dc63f9cccb7371cfd927dbac08bbe4cbf36ef6df..f5f832f3522fadea80afbd152517eb1f59927d60 100644 (file)
@@ -2,41 +2,28 @@
 
 module Main(main) where
 
-import Text.Parsec hiding (State)
--- import Text.ParserCombinators.Parsec.Number
-
-
+import Data.Char (digitToInt)
 
 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)
-
-
-up   = char '(' *> pure 1
-down = char ')' *> pure -1
-
--- parseIfile :: String -> Either ParseError [[Int]]
--- parseIfile input = parse instructionFile "(unknown)" input
-
-parseIline :: String -> Either ParseError [Int]
-parseIline input = parse instructionLine "(unknown)" input
-
-successfulParse :: Either ParseError [a] -> [a]
-successfulParse (Left _) = []
-successfulParse (Right a) = a
+        digits <- readFile "data/advent01.txt"
+        print $ part1 digits
+        print $ part2 digits
+
+part1 :: String -> Int  
+part1 = solve 1
+
+part2 :: String -> Int  
+part2 digits = solve (length digits `div` 2) digits
+
+-- Verbose version
+-- solve n digits = sum $ map (digitToInt . fst) 
+--                      $ filter (uncurry (==)) 
+--                      $ zip digits 
+--                      $ drop n 
+--                      $ cycle digits
+
+solve :: Int -> String -> Int
+solve n digits = sum $ zipWith (\a b -> if a == b then digitToInt a else 0) digits 
+                     $ drop n 
+                     $ cycle digits