Skip to content

Instantly share code, notes, and snippets.

@JCBurnside
Created December 9, 2020 22:37
Show Gist options
  • Save JCBurnside/9176461cd7cc362f69cecf76f22141c3 to your computer and use it in GitHub Desktop.
Save JCBurnside/9176461cd7cc362f69cecf76f22141c3 to your computer and use it in GitHub Desktop.
aoc 2020 day 9
fn part1(data: &[u32], preamble_len: usize) -> u32 {
use itertools::Itertools;
data.iter()
.skip(preamble_len)
.enumerate()
.map(|(i, &datum)| {
(
data.iter()
.skip(i)
.take(preamble_len)
.copied()
.collect::<Vec<u32>>(),
datum,
)
})
.find(|(previous, datum)| {
!previous
.iter()
.cartesian_product(previous.iter())
.any(|(left, right)| left + right == *datum)
})
.unwrap()
.1
}
fn part2(data: &[u32], preamble_len: usize) -> u32 {
let target = part1(data, preamble_len);
let windows = (2..)
.find(|&windows| {
data.windows(windows)
.find(|it| it.iter().map(|&it| it as u64).sum::<u64>() == target as u64)
.is_some()
})
.unwrap();
if let Some(r) = data
.windows(windows)
.find(|it| it.iter().sum::<u32>() == target)
{
r.iter().min().unwrap() + r.iter().max().unwrap()
} else {
0
}
}
fn main() {
let data: Vec<u32> = include_str!("data.txt")
.lines()
.filter_map(|it| it.parse().ok())
.collect();
println!("first mismatch is {}", part1(&data, 25));
println!("weakness is {}", part2(&data, 25))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment