aoc2023

advent of code 2023
Log | Files | Refs | Feed | README

day6.hs (1461B)


      1 -- AOC 2023: Day 6 - Wait For It
      2 --
      3 -- Given a set of (time, distance) pairs, an acceleration of 1
      4 -- dist/time^2 (units don't matter), and the rule that while
      5 -- accelerating you are not moving find the number of different ways
      6 -- you can reach the distance (i.e. you accelerate for a some portion
      7 -- of the time and then travel at the achieved velocity for the
      8 -- remainder).
      9 --
     10 -- Example input:
     11 -- Time:      7  15   30
     12 -- Distance:  9  40  200
     13 -- Test Output: 288
     14 --
     15 -- Task 2: There is actually only one time and distance in the
     16 -- example input with some random space in between.
     17 -- Test Output: 71503
     18 --
     19 {-# LANGUAGE OverloadedStrings #-}
     20 
     21 import qualified Data.Text as T
     22 import qualified Data.Text.IO as TI
     23 import Text.Printf (printf)
     24 
     25 texttoint :: T.Text -> Int
     26 texttoint t = read (T.unpack t) :: Int
     27 
     28 numlist :: T.Text -> [Int]
     29 numlist = map texttoint . filter (/= "") . T.splitOn " " . T.strip
     30 
     31 winningwaits :: (Int, Int) -> Int
     32 winningwaits (t, d) = length $ [x | x <- [1 .. (t - 1)], x * (t - x) > d]
     33 
     34 main = do
     35     contents <- TI.getContents
     36     let (t, d) = T.breakOn "\n" contents
     37     let times = T.dropWhile (/= ' ') t
     38     let dists = T.dropWhile (/= ' ') d
     39     let pairs = zip (numlist times) (numlist dists)
     40     let pairs2 =
     41             ( texttoint $ T.filter (/= ' ') times
     42             , texttoint $ T.filter (/= ' ') dists)
     43     printf "Task 1: %8d\n" (foldl (*) 1 $ map winningwaits pairs)
     44     printf "Task 2: %8d\n" (winningwaits pairs2)