From a651f9ed80def3e5af965d6fd3130aa242523f4d Mon Sep 17 00:00:00 2001 From: Bauke Date: Wed, 6 Apr 2022 14:30:31 +0200 Subject: [PATCH] Solve two-sum. --- source/lib.rs | 1 + source/two_sum/mod.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 source/lib.rs create mode 100644 source/two_sum/mod.rs diff --git a/source/lib.rs b/source/lib.rs new file mode 100644 index 0000000..40aceb0 --- /dev/null +++ b/source/lib.rs @@ -0,0 +1 @@ +pub mod two_sum; diff --git a/source/two_sum/mod.rs b/source/two_sum/mod.rs new file mode 100644 index 0000000..e717137 --- /dev/null +++ b/source/two_sum/mod.rs @@ -0,0 +1,26 @@ +use std::convert::TryInto; + +pub fn two_sum(numbers: Vec, target: i32) -> Vec { + for (index_1, number_1) in numbers.iter().enumerate() { + for (index_2, number_2) in numbers.iter().enumerate() { + if index_1 == index_2 { + continue; + } + + if number_1 + number_2 == target { + return vec![index_1.try_into().unwrap(), index_2.try_into().unwrap()]; + } + } + } + + panic!("No pair of numbers found that sum to {}", target) +} + +#[test] +fn test_two_sum() { + assert_eq!(two_sum(vec![2, 7, 11, 15], 9), [0, 1]); + assert_eq!(two_sum(vec![3, 2, 4], 6), [1, 2]); + assert_eq!(two_sum(vec![3, 3], 6), [0, 1]); + assert_eq!(two_sum(vec![3, 2, 3], 6), [0, 2]); + assert_eq!(two_sum(vec![-3, 4, 3, 90], 0), [0, 2]); +}