Skip to content

Commit

Permalink
Solve day 6
Browse files Browse the repository at this point in the history
  • Loading branch information
ricohageman committed Dec 6, 2023
1 parent ba5a336 commit eb8882b
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.

<!--- advent_readme_stars table --->

<!--- benchmarking table --->
## 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**
<!--- benchmarking table --->

---
Expand Down
2 changes: 2 additions & 0 deletions data/examples/06.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200
72 changes: 72 additions & 0 deletions src/bin/06.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use itertools::Itertools;
advent_of_code::solution!(6);

fn line_as_numbers(line: &str) -> Vec<usize> {
line.split_once(": ")
.unwrap()
.1
.split(' ')
.filter(|time| !time.is_empty())
.map(|time| time.parse().unwrap())
.collect()
}

pub fn part_one(input: &str) -> Option<usize> {
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::<Vec<usize>>()
.into_iter()
.rev()
.enumerate()
.map(|(index, value)| 10_usize.pow(index as u32) * value)
.sum()
}

pub fn part_two(input: &str) -> Option<usize> {
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));
}
}

0 comments on commit eb8882b

Please sign in to comment.