Add 2020 day 13

This commit is contained in:
Xavier Morel
2020-12-13 15:55:48 +01:00
parent e875879be6
commit 518852accb
4 changed files with 36 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
1000510
19,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,523,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,17,13,x,x,x,x,x,x,x,x,x,x,29,x,853,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,23

View File

@@ -0,0 +1,2 @@
939
7,13,x,x,59,x,31,19

View File

@@ -0,0 +1,30 @@
module Y2020.Day13 (y20day13) where
import Data.List
import Data.List.Split
import Data.Function (on)
timeToWait :: Int -> Int -> Int
timeToWait mytime bustime = time_to_next_pass
where time_since_last_pass = mytime `mod` bustime
time_to_next_pass = bustime - time_since_last_pass
-- timestamp, step -> offset, busid -> timestamp, step
lowestTS :: (Int, Int) -> (Int, Int) -> (Int, Int)
lowestTS (0, 0) (_, busid) = (busid, busid)
lowestTS (curTS, step) (offset, busid)
| (curTS + offset) `mod` busid == 0 = (curTS, step * busid)
| otherwise = lowestTS (curTS + step, step) (offset, busid)
y20day13 :: [String] -> (String, String)
y20day13 [arrival', busids'] = (part1, part2)
where part1 = show $ next_bus_id * next_bus_time
part2 = show $ timestamp
arrival = read arrival' :: Int
(next_bus_id, next_bus_time) = minimumBy (compare `on` snd) $ map (\busid -> (busid, timeToWait arrival busid)) busids :: (Int, Int)
busids = map read $ filter (/="x") $ splitOn "," busids' :: [Int]
busIdWithOffset = map (\(a, b) -> (a, read b :: Int)) $ filter ((/= "x") . snd) $ zip (iterate (+1) 0) $ splitOn "," busids'
timestamp = foldl lowestTS (0, 0) busIdWithOffset

View File

@@ -12,6 +12,7 @@ import Y2020.Day09
import Y2020.Day10 import Y2020.Day10
import Y2020.Day11 import Y2020.Day11
import Y2020.Day12 import Y2020.Day12
import Y2020.Day13
year2020 :: String -> [String] -> (String, String) year2020 :: String -> [String] -> (String, String)
year2020 "01" = y20day01 year2020 "01" = y20day01
@@ -26,3 +27,4 @@ year2020 "09" = y20day09
year2020 "10" = y20day10 year2020 "10" = y20day10
year2020 "11" = y20day11 year2020 "11" = y20day11
year2020 "12" = y20day12 year2020 "12" = y20day12
year2020 "13" = y20day13