1
Fork 0

Solve two-sum.

This commit is contained in:
Bauke 2022-04-06 14:30:31 +02:00
parent 763a55bab8
commit a651f9ed80
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
2 changed files with 27 additions and 0 deletions

1
source/lib.rs Normal file
View File

@ -0,0 +1 @@
pub mod two_sum;

26
source/two_sum/mod.rs Normal file
View File

@ -0,0 +1,26 @@
use std::convert::TryInto;
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
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]);
}