Hello everyone! I am a beginner of rust. I am trying to exercise iterator and HashMap. There is something I can not understand and can't solve.
I am trying to write about finding a number that can be added by which two numbers in the array.
fn main() {
let cumulus = vec![3, 1,4,1,5,9, // 5
2,6,5,3,5, 8,9,7,9,3, // 15
2,3,8,4,6, 2,6,4,3,3, // 25
8,3,2,7,9, 5,0,2,8,8, // 35
4,1,9,7,1, 6,9,3,9,9, // 45
3,7,5,1,0, 5,8,2,0,9, // 55
7,4,9,4,4, 5,9,2,3,0, // 65
7,8,1,6,4, 0,6,2,8,6, // 75
2,0,8,9,9, 8,6,2,8,0, // 85
3,4,8,2,5, 3,4,2,1,1, // 95
7,0,6,7,9];
let n:i32 = 18;
let a = find_num_combine(&cumulus, &n, 2).expect("Error");
println!("{:?}", a);
}
fn find_num_combine<T>(amass: &Vec<T>, target: &T, parts: usize) -> Result<Vec<Vec<usize>>, String>
where T: Sub<Output=T> + Copy + Eq + Hash
{
let empty_or_return = |result: Vec<Vec<usize>>| {
match result.len() {
0 => Err("Can not find target".to_string()),
_ => Ok(result)
} };
if parts >= 3 {
// let result:Vec<Vec<usize>> = Vec::new();
todo!();
// empty_or_return(result)
} else if parts == 2 {
let mut result:Vec<Vec<usize>> = Vec::new();
let mut happy_map:HashMap<T,usize> = HashMap::new();
amass.iter().enumerate().for_each(|(index, value)| {
happy_map.iter().for_each(|(k,v)| {
if *target - *value == *k {
result.push(vec![index, *v]);
} } );
happy_map.entry(*value).or_insert(index); } );
empty_or_return(result)
} else if parts == 1 {
empty_or_return(
amass.iter()
.enumerate()
.filter(|&(_, value)| *value == *target)
.map(|(index, _)| vec![index])
.collect())
} else { Err("At least parts >= 1".to_string()) }
}
The program only print something as below. Why there is no [14, 12].
[[12, 5], [14, 5], [30, 5], [38, 5], [42, 5], [44, 5], [45, 5], [55, 5], [58, 5], [62, 5], [79, 5], [80, 5], [100, 5]]