From 649581c12a4d7364cbebe1baef79d9a9260b14b6 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Tue, 1 Dec 2020 19:53:15 -0800 Subject: [PATCH] Solution to 2020 puzzle 2. --- 2020/src/bin/1.rs | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/2020/src/bin/1.rs b/2020/src/bin/1.rs index c833a44..f9107c3 100644 --- a/2020/src/bin/1.rs +++ b/2020/src/bin/1.rs @@ -34,13 +34,21 @@ fn main() -> Result<()> { .nth(1) .ok_or(anyhow!("Usage: 1 "))?; let nums = parse(path)?; - let pair = find_2020(nums).ok_or(anyhow!("Couldn't find pairs summing to 2020"))?; + let pair = find_pair_2020(&nums).ok_or(anyhow!("Couldn't find pairs summing to 2020"))?; println!("Product of {} x {} = {}", pair.0, pair.1, pair.0 * pair.1); + let triple = find_triple_2020(&nums).ok_or(anyhow!("Couldn't find triples summing to 2020"))?; + println!( + "Product of {} x {} x {} = {}", + triple.0, + triple.1, + triple.2, + triple.0 * triple.1 * triple.2 + ); Ok(()) } /// Finds pairs of numbers in `nums` that sum to 2020. If no pairs are found, `None` is returned. -fn find_2020(nums: Vec) -> Option<(u32, u32)> { +fn find_pair_2020(nums: &Vec) -> Option<(u32, u32)> { for (idx, first) in nums.iter().enumerate() { for second in nums.iter().skip(idx + 1) { if first + second == 2020 { @@ -51,6 +59,20 @@ fn find_2020(nums: Vec) -> Option<(u32, u32)> { None } +/// Finds triple of numbers in `nums` that sum to 2020. If no triple is found, `None` is returned. +fn find_triple_2020(nums: &Vec) -> Option<(u32, u32, u32)> { + for (idx1, first) in nums.iter().enumerate() { + for (idx2, second) in nums.iter().enumerate().skip(idx1 + 1) { + for third in nums.iter() { + if first + second + third == 2020 { + return Some((*first, *second, *third)); + } + } + } + } + None +} + /// Reads text file containing one integer per line, and parses them into `Vec`. Any /// non-number will result in an error returned. fn parse>(path: P) -> Result> { @@ -75,8 +97,14 @@ mod tests { } #[test] - fn test_find_2020() { + fn test_find_pair_2020() { let nums = parse("src/bin/1-test.txt").expect("failed to parse"); - assert_eq!(find_2020(nums), Some((1721, 299))); + assert_eq!(find_pair_2020(&nums), Some((1721, 299))); + } + + #[test] + fn test_find_triple_2020() { + let nums = parse("src/bin/1-test.txt").expect("failed to parse"); + assert_eq!(find_triple_2020(&nums), Some((979, 366, 675))); } }