Skip to content

Commit

Permalink
Day 9 - Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
tudorpavel committed Dec 9, 2020
1 parent 618b24c commit 079521a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
6 changes: 6 additions & 0 deletions day09/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,9 @@ https://adventofcode.com/2020/day/9
This might be a good opportunity to use [std::slice::Windows](https://doc.rust-lang.org/std/primitive.slice.html#method.windows) to interate over a 26-length slice. Inside each slice we can brute force check all possible pairs from first 25 elements and compare their sum to the 26th element. I'm not sure if there's a more performant solution than brute-forcing it.

Also of note is that we need to use 64-bit unsigned integer values from what I can see in my input.

## Part 2

We can brute-force this part as well by generating and iterating progressively larger windows into the input and comparing their sum to the result from Part 1.

This solution seems fast enough, I don't think it's worth trying to optimize it.
29 changes: 22 additions & 7 deletions day09/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,39 @@ fn has_valid_sum(prev_nums: &[u64], reference: u64) -> bool {
false
}

fn solve(lines: Vec<String>, preamble_size: usize) -> u64 {
fn solve(lines: Vec<String>, preamble_size: usize) -> (u64, u64) {
let nums: Vec<u64> = lines.iter().map(|l| l.parse().unwrap()).collect();
let mut part1 = 0;

// Part 1
for window in nums.windows(preamble_size + 1) {
let reference = *window.last().unwrap();
part1 = *window.last().unwrap();

if !has_valid_sum(&window[..preamble_size], reference) {
return reference;
if !has_valid_sum(&window[..preamble_size], part1) {
break;
}
}

0
// Part 2
for window_size in 2..=lines.len() {
for window in nums.windows(window_size) {
if window.iter().sum::<u64>() == part1 {
return (
part1,
window.iter().min().unwrap() + window.iter().max().unwrap(),
);
}
}
}

(part1, 0)
}

fn main() {
let lines = utils::read_lines();
let part1 = solve(lines, 25);
let (part1, part2) = solve(lines, 25);
println!("Part 1: {}", part1);
println!("Part 2: {}", part2);
}

#[cfg(test)]
Expand All @@ -47,7 +62,7 @@ mod tests {
.collect(),
5
),
127
(127, 62)
);
}
}

0 comments on commit 079521a

Please sign in to comment.