feat(day2): Implement part 1
This commit is contained in:
parent
38ff90154f
commit
cb83e4247d
49
day2/Main.hs
Normal file
49
day2/Main.hs
Normal file
|
@ -0,0 +1,49 @@
|
|||
module Main where
|
||||
|
||||
import System.Environment (getArgs)
|
||||
|
||||
import Text.Parsec (parse, many1, char, sepBy, endBy)
|
||||
import Text.Parsec.Char (endOfLine)
|
||||
import Text.ParserCombinators.Parsec (GenParser)
|
||||
import Text.ParserCombinators.Parsec.Number (decimal)
|
||||
|
||||
type Report = [Level]
|
||||
type Level = Int
|
||||
|
||||
reports :: GenParser Char st [Report]
|
||||
reports = endBy report endOfLine
|
||||
|
||||
report :: GenParser Char st Report
|
||||
report = sepBy level (many1 (char ' '))
|
||||
|
||||
level :: GenParser Char st Level
|
||||
level = decimal
|
||||
|
||||
pairUp :: [a] -> [(a, a)]
|
||||
pairUp (a:b:tl) = (a, b) : pairUp (b:tl)
|
||||
pairUp _ = []
|
||||
|
||||
allIncOrDec :: Report -> Bool
|
||||
allIncOrDec (a:b:tl)
|
||||
| a /= b = all (uncurry (if a < b then (<) else (>))) $ pairUp $ b:tl
|
||||
| otherwise = False
|
||||
allIncOrDec _ = True
|
||||
|
||||
notTooDifferent :: Report -> Bool
|
||||
notTooDifferent (a:b:tl) = let dif = abs (a - b)
|
||||
in (1 <= dif) && (dif <= 3) && notTooDifferent (b:tl)
|
||||
notTooDifferent _ = True
|
||||
|
||||
part1 :: [Report] -> Int
|
||||
part1 = length . filter allIncOrDec . filter notTooDifferent
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
args <- getArgs
|
||||
(fp:_) <- return args
|
||||
content <- readFile fp
|
||||
case parse reports fp content of
|
||||
Left e -> putStrLn ("Input file is incorrectly formatted : " ++ show e)
|
||||
Right r -> do
|
||||
putStrLn ("Solution (Part 1) : " ++ show (part1 r))
|
||||
-- putStrLn ("Solution (Part 2) : " ++ show (part2 r))
|
1000
day2/puzzle_input
Normal file
1000
day2/puzzle_input
Normal file
File diff suppressed because it is too large
Load diff
6
day2/test_input
Normal file
6
day2/test_input
Normal file
|
@ -0,0 +1,6 @@
|
|||
7 6 4 2 1
|
||||
1 2 7 8 9
|
||||
9 7 6 2 1
|
||||
1 3 2 4 5
|
||||
8 6 4 4 1
|
||||
1 3 6 7 9
|
|
@ -21,3 +21,13 @@ executable day1
|
|||
parsec-numbers ^>= 0.1.0
|
||||
hs-source-dirs: day1
|
||||
default-language: Haskell2010
|
||||
|
||||
executable day2
|
||||
import: warnings
|
||||
main-is: Main.hs
|
||||
build-depends:
|
||||
base ^>=4.18.2.1,
|
||||
parsec ^>= 3.1.17.0,
|
||||
parsec-numbers ^>= 0.1.0
|
||||
hs-source-dirs: day2
|
||||
default-language: Haskell2010
|
||||
|
|
Loading…
Reference in a new issue