This problem is very easy, but there are some usages that we can learn.
Topic Requirements:
Find the number of positive numbers in a vector, and the number of negative numbers.
First, the solution
fn count_positives_sum_negatives (input:vec<i32>)-> vec<i32> {let
_up =
input.iter (). Filter ( |&x| *x > 0) .collect::<vec<_>> () ITER () fold (0, |total, &x| total + x);
Let _down =
input.iter (). Filter (|&x| *x < 0) .collect::<vec<_>> (). ITER (). Fold (0, |total, &x | Total + x);
Vec! [_up, _down]
}
I also made some efforts to one-step, but did not succeed.
Such as:
The following are non valid code attempts 1
fn count_positives_sum_negatives2 (input:vec<i32>)-> vec<i32> {
input.iter (). Fold ((0, 0), | ( Mut total, Mut num), &x| Match x > 0 {
true => total = 1,
_ => num + = x,
})
}
The following are non valid code attempts 2
fn count_positives_sum_negatives2 (input:vec<i32>)-> vec<i32> {
input.iter (). Fold ((0, 0), |mut Total, &x| match x > 0 {
true => total.0 = 1,
_ => total.1 = x,
})
}
In fact, try 2 Some quick close to success ...
Using the solution of other people in Codewars, we can run the
fn count_positives_sum_negatives2 (input:vec<i32>)-> vec<i32> {
input.iter (). Fold (vec![ 0, 0], |mut total, &x| {
match x > 0 {
true => total[0] = 1,
_ => total[1] = = x, total
})
}
Second, the Codewars wonderful solution
1,
fn count_positives_sum_negatives (input:vec<i32>)-> vec<i32> {
if Input.is_empty () {
return Vec! [];
}
Input.iter (). Fold (vec![ 0, 0], |mut ACC, &x| {
if x > 0 {
acc[0] = 1;
} else {
acc[1] = x;
}
ACC
})
}
2,
fn count_positives_sum_negatives (input:vec<i32>)-> vec<i32> {if input.len () = = 0 {return Vec :: New ()} input.into_iter (). fold ([0,0], |mut sum, i| {if i > 0 {sum[0] + 1} else if I < 0 {sum[1] = i} sum}). As_ref (). into ()}