Added Solution for 2023 day 06

This commit is contained in:
Burnus 2023-12-06 19:31:05 +01:00
parent 57ac52e303
commit 6f5a1cf606
6 changed files with 213 additions and 0 deletions

View file

@ -0,0 +1,8 @@
[package]
name = "day06_wait_for_it"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,81 @@
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.
For example:
```
Time: 7 15 30
Distance: 9 40 200
```
This document describes three races:
* The first race lasts 7 milliseconds. The record distance in this race is 9 millimeters.
* The second race lasts 15 milliseconds. The record distance in this race is 40 millimeters.
* The third race lasts 30 milliseconds. The record distance in this race is 200 millimeters.
Your toy boat has a starting speed of *zero millimeters per millisecond*. For each whole millisecond you spend at the beginning of the race holding down the button, the boat's speed increases by *one millimeter per millisecond*.
So, because the first race lasts 7 milliseconds, you only have a few options:
* Don't hold the button at all (that is, hold it for *`0` milliseconds*) at the start of the race. The boat won't move; it will have traveled *`0` millimeters* by the end of the race.
* Hold the button for *`1` millisecond* at the start of the race. Then, the boat will travel at a speed of `1` millimeter per millisecond for 6 milliseconds, reaching a total distance traveled of *`6` millimeters*.
* Hold the button for *`2` milliseconds*, giving the boat a speed of `2` millimeters per millisecond. It will then get 5 milliseconds to move, reaching a total distance of *`10` millimeters*.
* Hold the button for *`3` milliseconds*. After its remaining 4 milliseconds of travel time, the boat will have gone *`12` millimeters*.
* Hold the button for *`4` milliseconds*. After its remaining 3 milliseconds of travel time, the boat will have gone *`12` millimeters*.
* Hold the button for *`5` milliseconds*, causing the boat to travel a total of *`10` millimeters*.
* Hold the button for *`6` milliseconds*, causing the boat to travel a total of *`6` millimeters*.
* Hold the button for *`7` milliseconds*. That's the entire duration of the race. You never let go of the button. The boat can't move until you let go of the button. Please make sure you let go of the button so the boat gets to move. *`0` millimeters*.
Since the current record for this race is `9` millimeters, there are actually `*4*` different ways you could win: you could hold the button for `2`, `3`, `4`, or `5` milliseconds at the start of the race.
In the second race, you could hold the button for at least `4` milliseconds and at most `11` milliseconds and beat the record, a total of `*8*` different ways to win.
In the third race, you could hold the button for at least `11` milliseconds and no more than `19` milliseconds and still beat the record, a total of `*9*` ways you could win.
To see how much margin of error you have, determine the *number of ways you can beat the record* in each race; in this example, if you multiply these values together, you get `*288*` (`4` \* `8` \* `9`).
Determine the number of ways you could beat the record in each race. *What do you get if you multiply these numbers together?*
Your puzzle answer was `252000`.
\--- Part Two ---
----------
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](https://en.wikipedia.org/wiki/Kerning). There's really *only one race* - ignore the spaces between the numbers on each line.
So, the example from before:
```
Time: 7 15 30
Distance: 9 40 200
```
...now instead means this:
```
Time: 71530
Distance: 940200
```
Now, you have to figure out how many ways there are to win this single race. In this example, the race lasts for *`71530` milliseconds* and the record distance you need to beat is *`940200` millimeters*. You could hold the button anywhere from `14` to `71516` milliseconds and beat the record, a total of `*71503*` ways!
*How many ways can you beat the record in this one much longer race?*
Your puzzle answer was `36992486`.
Both parts of this puzzle are complete! They provide two gold stars: \*\*
At this point, you should [return to your Advent calendar](/2023) and try another puzzle.
If you still want to see it, you can [get your puzzle input](6/input).

Binary file not shown.

View file

@ -0,0 +1,120 @@
use core::fmt::Display;
use std::num::ParseIntError;
#[derive(Debug, PartialEq, Eq)]
pub enum ParseError<'a> {
UnequalInputLength(usize, usize),
ParseIntError(std::num::ParseIntError),
LineMalformed(&'a str),
InputMustBeTwoLines(&'a str),
}
impl From<ParseIntError> for ParseError<'_> {
fn from(value: ParseIntError) -> Self {
Self::ParseIntError(value)
}
}
impl Display for ParseError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InputMustBeTwoLines(i) => write!(f, "Input has to be exactly 2 lines long, but was \"{i}\""),
Self::LineMalformed(v) => write!(f, "Line is malformed: {v}"),
Self::ParseIntError(e) => write!(f, "Unable to parse into integer: {e}"),
Self::UnequalInputLength(t, d) => write!(f, "Input had a different number of values for both lines: {t} times but {d} distances"),
}
}
}
struct Race {
time: usize,
distance: usize,
}
fn try_into_races(input: &str) -> Result<Vec<Race>, ParseError> {
let lines: Vec<_> = input.lines().collect();
if lines.len() != 2 {
return Err(ParseError::InputMustBeTwoLines(input));
}
let times: Vec<_> = lines[0].split_whitespace().skip(1).map(|n| n.parse::<usize>()).collect::<Result<Vec<_>, ParseIntError>>()?;
let distances: Vec<_> = lines[1].split_whitespace().skip(1).map(|n| n.parse::<usize>()).collect::<Result<Vec<_>, ParseIntError>>()?;
if times.len() != distances.len() {
return Err(ParseError::UnequalInputLength(times.len(), distances.len()));
}
Ok((0..times.len()).map(|idx| Race { time: times[idx], distance: distances[idx], }).collect::<Vec<_>>())
}
fn count_winning_strategies(race: &Race) -> usize {
// find the minimum time we need to press the button in order to beat the record, using
// newton's method
let est_cutoff = estimate_cutoff(race.time as f64, race.distance as f64, 0.0);
// find the actual minimum by trying the close integers.
let cutoff = (est_cutoff-(2.min(est_cutoff))..=est_cutoff+2).find(|t| t*(race.time-t) > race.distance).unwrap();
// since the function is symetric around race.time/2, we know the maximum time we can press the
// button is race.time-cutoff, so we can easily calculate the count of integers in the range:
// (cutoff..=race.time-cutoff).count() ==
// (0..=race.time-(2*cutoff)).count() ==
// (1..=race.time-(2*cutoff)+1).count() ==
// (race.time-2*cutoff)+1
race.time+1-2*cutoff
}
fn estimate_cutoff(time: f64, distance: f64, x: f64) -> usize {
let y = x * (time-x) - distance;
if y.abs() < 0.5 {
return x.round() as usize;
}
let dy = (x+1.0) * (time-(x+1.0)) - (distance + y);
estimate_cutoff(time, distance, x-y/dy)
}
fn fix_kerning(races: &[Race]) -> Race {
let mut time = 0;
let mut distance = 0;
races.iter().for_each(|race| {
let mut time_multiplier = 10;
while time_multiplier <= race.time {
time_multiplier *= 10;
}
time = time * time_multiplier + race.time;
let mut distance_multiplier = 10;
while distance_multiplier <= race.distance {
distance_multiplier *= 10;
}
distance = distance * distance_multiplier + race.distance;
});
Race {
time,
distance,
}
}
pub fn run(input: &str) -> Result<(usize, usize), ParseError> {
let races: Vec<_> = try_into_races(input)?;
let first = races.iter().map(count_winning_strategies).product();
let the_race = fix_kerning(&races);
let second = count_winning_strategies(&the_race);
Ok((first, second))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::read_to_string;
fn read_file(name: &str) -> String {
read_to_string(name).expect(&format!("Unable to read file: {name}")[..]).trim().to_string()
}
#[test]
fn test_sample() {
let sample_input = read_file("tests/sample_input");
assert_eq!(run(&sample_input), Ok((288, 71503)));
}
#[test]
fn test_challenge() {
let challenge_input = read_file("tests/challenge_input");
assert_eq!(run(&challenge_input), Ok((252000, 36992486)));
}
}

View file

@ -0,0 +1,2 @@
Time: 48 87 69 81
Distance: 255 1288 1117 1623

View file

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200