aboutsummaryrefslogtreecommitdiff
path: root/2020/13a.hs
diff options
context:
space:
mode:
authorAria <me@aria.rip>2023-01-02 21:58:56 +0000
committerAria <me@aria.rip>2023-01-02 21:58:56 +0000
commit5eb58ad076f2cd435b11b140820da224b60b73d5 (patch)
tree2a67939595fbf993ff04f69b9cd3f0aa20827d96 /2020/13a.hs
initial commit
Diffstat (limited to '2020/13a.hs')
-rw-r--r--2020/13a.hs45
1 files changed, 45 insertions, 0 deletions
diff --git a/2020/13a.hs b/2020/13a.hs
new file mode 100644
index 0000000..1346a68
--- /dev/null
+++ b/2020/13a.hs
@@ -0,0 +1,45 @@
+module Day13A where
+
+import System.Environment (getArgs)
+import Data.Maybe (catMaybes)
+import Data.List.Split (splitOn)
+import Text.Read (readMaybe)
+import Text.Printf
+
+-- Get the nearest bus in the list after the given time
+-- Returns (time, bus)
+getNearest :: Int -> [Int] -> (Int, Int)
+getNearest e xs | not $ null rs = (e, head rs)
+ | otherwise = getNearest (e + 1) xs
+ where rs = filter (\x -> e `mod` x == 0) xs
+
+-- Parse the input as a string
+-- Returns (current time, list of valid buses)
+parseInput :: String -> (Int, [Int])
+parseInput x = (read t, catMaybes ts)
+ where (t:r) = lines x
+ bs = splitOn "," (head r)
+ ts :: [Maybe Int]
+ ts = map readMaybe bs
+
+-- Parse a file given the path
+-- Returns (current time, list of valid buses)
+parseFromFile :: String -> IO (Int, [Int])
+parseFromFile s = do
+ contents <- readFile s;
+ return $ parseInput contents;
+
+-- runghc --ghc-arg='-package split' 13a.hs inputs/day13
+main :: IO ()
+main = do
+ args <- getArgs;
+ (now, bs) <- parseFromFile (head args);
+
+ let (t, b) = getNearest now bs;
+ let w = t - now;
+
+ printf "You could get bus %d at %d\n" b t :: IO ();
+ printf "This is a %d minute wait\n" w :: IO ();
+ printf "Answer = %d\n" (b * w) :: IO ();
+
+ return ();