improve 2020/01

This commit is contained in:
kageru 2020-12-01 23:54:58 +01:00
parent 9932b57d24
commit 3dfcc6fad7
Signed by: kageru
GPG Key ID: 8282A2BEA4ADA3D2

View File

@ -1,3 +1,4 @@
#![feature(bool_to_option)]
use itertools::Itertools;
use std::io::BufRead;
@ -10,32 +11,16 @@ fn main() {
let p1 = input
.iter()
.tuple_combinations()
.filter(|(&a, &b)| a + b == 2020)
.map(|(a, b)| a * b)
.next()
.find_map(|(&a, &b)| (a + b == 2020).then_some(a * b))
.unwrap();
println!("Part 1: {}", p1);
/*
smol-brain, n³ solution:
let p2 = input
.tuple_combinations()
.filter(|(&a, &b, &c)| a + b + c == 2020)
.map(|(a, b, c)| a * b * c)
.next()
.unwrap();
println!("Part 2: {}", p2);
*/
// Ascended n² solution (thanks to Lypheo)
let mut p2_table = vec![None; 2020];
for (&a, &b) in input.iter().tuple_combinations() {
if a + b < 2020 {
p2_table[a + b] = Some((a, b))
}
}
let (a, b) = input
.iter()
.filter_map(|x| p2_table[2020 - x])
.next()
.unwrap();
let (a, b) = input.iter().find_map(|x| p2_table[2020 - x]).unwrap();
println!("Part 2: {}", a * b * (2020 - a - b));
}