Skip to content

Commit

Permalink
aoc2023/day6: Update solution
Browse files Browse the repository at this point in the history
Signed-off-by: Andrej Orsula <orsula.andrej@gmail.com>
  • Loading branch information
AndrejOrsula committed Dec 6, 2023
1 parent e50d2ee commit bcd6c5a
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ My solutions to [Advent of Code](https://adventofcode.com) puzzles.
| 0.419 µs | 308.1 µs |
| 53.39 µs | 28.44 µs |
| 16.38 µs | 19.364 s |
| 0.513 µs | 2.463 ms |
| 0.513 µs | 0.650 µs |

</td></tr>
</table>
Expand Down
1 change: 1 addition & 0 deletions aoc2023/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ aoc-runner-derive = { workspace = true }
indoc = { workspace = true }

itertools = { version = "0.12" }
num-integer = { version = "0.1" }
rayon = { version = "1.8" }
regex = { version = "1.10" }
smallvec = { version = "1.11" }
Expand Down
12 changes: 11 additions & 1 deletion aoc2023/src/day6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ mod utils {
}

impl RaceData {
/// Solver using brute force (faster than the quadratic formula for small inputs).
pub fn n_record_breaks(&self) -> u64 {
let (time, distance) = (self.time.parse().unwrap(), self.distance.parse().unwrap());
match (1..time).find(|j| j * (time - j) > distance) {
Expand All @@ -34,6 +35,15 @@ mod utils {
}
}

/// Solver based on quadratic formula (much faster than brute force for large inputs).
pub fn n_record_breaks1(&self) -> u64 {
let (time, distance) = (
self.time.parse::<u64>().unwrap(),
self.distance.parse::<u64>().unwrap(),
);
2 * num_integer::sqrt(time.pow(2) / 4 - distance - 1) + (time % 2) + 1
}

pub fn merge(sequence: &[Self]) -> Self {
let (time, distance) = sequence.iter().fold(
Default::default(),
Expand All @@ -53,7 +63,7 @@ fn part1(input: &[utils::RaceData]) -> u64 {

#[aoc(day6, part2)]
fn part2(input: &[utils::RaceData]) -> u64 {
utils::RaceData::merge(input).n_record_breaks()
utils::RaceData::merge(input).n_record_breaks1()
}

#[cfg(test)]
Expand Down

0 comments on commit bcd6c5a

Please sign in to comment.