From eb8882b0a703d69fb02b7fe79083c5f69175fb6b Mon Sep 17 00:00:00 2001 From: Rico Hageman Date: Wed, 6 Dec 2023 23:02:04 +0100 Subject: [PATCH] Solve day 6 --- README.md | 13 ++++++++ data/examples/06.txt | 2 ++ src/bin/06.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 data/examples/06.txt create mode 100644 src/bin/06.rs diff --git a/README.md b/README.md index 85aba56..ff07175 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,19 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. + +## Benchmarks + +| Day | Part 1 | Part 2 | +| :---: | :---: | :---: | +| [Day 1](./src/bin/01.rs) | `86.5µs` | `945.9µs` | +| [Day 2](./src/bin/02.rs) | `48.9µs` | `61.7µs` | +| [Day 3](./src/bin/03.rs) | `575.5µs` | `527.0µs` | +| [Day 4](./src/bin/04.rs) | `295.7µs` | `274.8µs` | +| [Day 5](./src/bin/05.rs) | `24.2µs` | `91.1µs` | +| [Day 6](./src/bin/06.rs) | `410.0ns` | `5.4ms` | + +**Total: 8.33ms** --- diff --git a/data/examples/06.txt b/data/examples/06.txt new file mode 100644 index 0000000..b39f49d --- /dev/null +++ b/data/examples/06.txt @@ -0,0 +1,2 @@ +Time: 7 15 30 +Distance: 9 40 200 \ No newline at end of file diff --git a/src/bin/06.rs b/src/bin/06.rs new file mode 100644 index 0000000..0a09893 --- /dev/null +++ b/src/bin/06.rs @@ -0,0 +1,72 @@ +use itertools::Itertools; +advent_of_code::solution!(6); + +fn line_as_numbers(line: &str) -> Vec { + line.split_once(": ") + .unwrap() + .1 + .split(' ') + .filter(|time| !time.is_empty()) + .map(|time| time.parse().unwrap()) + .collect() +} + +pub fn part_one(input: &str) -> Option { + let mut lines = input.lines(); + let times = line_as_numbers(lines.next().unwrap()); + let records = line_as_numbers(lines.next().unwrap()); + + Some( + times + .into_iter() + .zip_eq(records) + .map(|(time, record)| { + (1..time) + .filter(|hold| (time - hold) * hold > record) + .count() + }) + .product(), + ) +} + +fn line_as_single_number(line: &str) -> usize { + line.split_once(": ") + .unwrap() + .1 + .chars() + .filter(|char| *char != ' ') + .map(|time| time.to_digit(10).unwrap() as usize) + .collect::>() + .into_iter() + .rev() + .enumerate() + .map(|(index, value)| 10_usize.pow(index as u32) * value) + .sum() +} + +pub fn part_two(input: &str) -> Option { + let mut lines = input.lines(); + let time = line_as_single_number(lines.next().unwrap()); + let record = line_as_single_number(lines.next().unwrap()); + + (1..time) + .find(|hold| (time - hold) * hold > record) + .map(|first| time - (2 * first) + 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(288)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(71503)); + } +}