From 6a3286c7c67368c56fa1a7c2b6934c29a0632687 Mon Sep 17 00:00:00 2001 From: Avril Date: Tue, 1 Dec 2020 23:06:24 +0000 Subject: [PATCH] day1: rust part1 reimpl --- day1/day1/Cargo.toml | 5 +++++ day1/day1/src/main.rs | 46 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/day1/day1/Cargo.toml b/day1/day1/Cargo.toml index 781048b..10e8202 100644 --- a/day1/day1/Cargo.toml +++ b/day1/day1/Cargo.toml @@ -7,6 +7,11 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] +default = ["part1"] + +part1 = [] +part2 = [] + big = ["u128"] u128 = [] diff --git a/day1/day1/src/main.rs b/day1/day1/src/main.rs index fcf6d7f..f529bd5 100644 --- a/day1/day1/src/main.rs +++ b/day1/day1/src/main.rs @@ -11,14 +11,47 @@ use input::INPUT; #[cfg(not(feature="big"))] const TARGET: u64 = 2020; #[cfg(feature="big")] const TARGET: u64 = 99920044; -// O(n^2) ? -fn main() { - // doesn't work on big input? +#[cfg(feature="part1")] +// O(2n) ? +fn part1() +{ + // u64 doesn't work on big input? + #[cfg(feature="u128")] + let input: Box<[_]> = INPUT[..].iter().map(|&x| x as u128).collect(); + #[cfg(feature="u128")] + let target = TARGET as u128; + + #[cfg(not(feature="u128"))] + let input = &INPUT[..]; + #[cfg(not(feature="u128"))] + let target = TARGET; + + let deficits: HashMap<_, usize> = (0..) + .zip(input.iter().copied()) + .filter_map(|(i, x)| target.checked_sub(x).map(|x| (x, i))) + .collect(); + + for ix in input.iter().copied() + { + if let Some(&idx) = deficits.get(&ix) + { + if let Some(x) = input[idx].checked_mul(ix) { + println!("{}", x); + return; + } + } + } + panic!("no solution"); +} +// O(n + n^2) ? +#[cfg(feature="part2")] +fn part2() +{ + // u64 doesn't work on big input? #[cfg(feature="u128")] let input: Box<[_]> = INPUT[..].iter().map(|&x| x as u128).collect(); #[cfg(feature="u128")] let target = TARGET as u128; - // ^ doesn't help.. #[cfg(not(feature="u128"))] let input = &INPUT[..]; @@ -48,3 +81,8 @@ fn main() { } panic!("no solution"); } + +fn main() { + #[cfg(feature="part1")] part1(); + #[cfg(feature="part2")] part2(); +}