2023 - Day 6: Wait For It

The ferry quickly brings you across Island Island. After asking around, you discover that there is indeed normally a large pile of sand somewhere near here, but you don’t see anything besides lots of water and the small island where the ferry has docked.

As you try to figure out what to do next, you notice a poster on a wall near the ferry dock. “Boat races! Open to the public! Grand prize is an all-expenses-paid trip to Desert Island!” That must be where the sand comes from! Best of all, the boat races are starting in just a few minutes.

You manage to sign up as a competitor in the boat races just in time. The organizer explains that it’s not really a traditional race - instead, you will get a fixed amount of time during which your boat has to travel as far as it can, and you win if your boat goes the farthest.

As part of signing up, you get a sheet of paper (your puzzle input) that lists the time allowed for each race and also the best distance ever recorded in that race. To guarantee you win the grand prize, you need to make sure you go farther in each race than the current record holder.

The organizer brings you over to the area where the boat races are held. The boats are much smaller than you expected - they’re actually toy boats, each with a big button on top. Holding down the button charges the boat, and releasing the button allows the boat to move. Boats move faster if their button was held longer, but time spent holding the button counts against the total race time. You can only hold the button at the start of the race, and boats don’t move until the button is released.

Set-Up

Code
races <- read.table("input.txt")

Part 1

To see how much margin of error you have, determine the number of ways you can beat the record in each race. Determine the number of ways you could beat the record in each race. What do you get if you multiply these numbers together?

Created a nice function to apply over the races (that was definitely vectorised before running Part 2 and not using a sapply to iterate).

Code
find_winning_races <- function(x) {
  time <- x[1]; distance <- x[2]
  times <- seq(time)
  distances <- (time - times) * times
  sum(distances > distance)
}

winning_times <- sapply(races[, -1], find_winning_races)
prod(winning_times)
[1] 128700

Part 2

As the race is about to start, you realize the piece of paper with race times and record distances you got earlier actually just has very bad kerning. There’s really only one race - ignore the spaces between the numbers on each line.

How many ways can you beat the record in this one much longer race?

A one liner! Using the function from Part 1, realised I got caught in the inefficient function, vectorised and was a lot quicker.

Code
find_winning_races(as.numeric(apply(races[, -1], 1, paste0, collapse = "")))
[1] 39594072