advent-of-code/2020/src/bin/day01.rs

61 lines
1.4 KiB
Rust
Raw Normal View History

2020-12-08 11:32:59 +01:00
#![feature(test, bool_to_option)]
2020-12-02 00:50:00 +01:00
extern crate test;
2020-12-01 08:02:29 +01:00
use itertools::Itertools;
2020-12-08 11:32:59 +01:00
use std::env;
2020-12-01 07:16:56 +01:00
2020-12-02 00:50:00 +01:00
fn read_input() -> Vec<usize> {
2020-12-10 12:44:07 +01:00
std::fs::read_to_string(
env::args()
.nth(1)
.filter(|n| n != "--bench")
.unwrap_or_else(|| String::from("inputs/day01")),
)
.unwrap()
.lines()
.filter_map(|l| l.parse().ok())
.collect()
2020-12-02 00:50:00 +01:00
}
2020-12-04 18:36:43 +01:00
fn part1(input: &[usize]) -> usize {
2020-12-02 00:50:00 +01:00
input
2020-12-01 08:02:29 +01:00
.iter()
.tuple_combinations()
2020-12-01 23:54:58 +01:00
.find_map(|(&a, &b)| (a + b == 2020).then_some(a * b))
2020-12-02 00:50:00 +01:00
.unwrap()
}
2020-12-01 23:54:58 +01:00
2020-12-04 18:36:43 +01:00
fn part2(input: &[usize]) -> usize {
2020-12-02 00:50:00 +01:00
let mut p2_table = [None; 2020];
2020-12-01 08:02:29 +01:00
for (&a, &b) in input.iter().tuple_combinations() {
2020-12-01 07:16:56 +01:00
if a + b < 2020 {
p2_table[a + b] = Some((a, b))
}
}
2020-12-01 23:54:58 +01:00
let (a, b) = input.iter().find_map(|x| p2_table[2020 - x]).unwrap();
2020-12-04 18:36:43 +01:00
a * b * (2020 - a - b)
2020-12-02 00:50:00 +01:00
}
fn main() {
let input = read_input();
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
#[cfg(test)]
mod tests {
use super::*;
use test::{black_box, Bencher};
#[bench]
fn bench_part1(b: &mut Bencher) {
let input = read_input();
b.iter(|| black_box(part1(black_box(&input))));
}
#[bench]
fn bench_part2(b: &mut Bencher) {
let input = read_input();
b.iter(|| black_box(part2(black_box(&input))));
}
2020-12-01 07:16:56 +01:00
}