Even Counter is the problem where we are given positive integers inside a Vec
, and we have to determine how many even numbers are inside the given Vec
.
I am thinking that this problem can be solved by:
- First, filter out the odd number from the
Vec
, so we only have even numbers left inside the givenVec
, - Second, Calculate the length of the filtered length
- Last, return that calculated value.
Despite it being a Vec
, we can use iterators to do it in one line without any for
, while
, or loop
loops. We could start by turning the Vec
into an Iterator
, then using some other methods as described below:
.iter()
converts theinput
Vec
into anIterator
.filter(|x| x % 2 == 0)
filters the even value (that satisfies the logicx % 2 == 0
in the closure) for the next calculation asIterator
.fold(0, |acc, _| acc + 1)
basically just sum on how many elements are present.acc
is the accumulated value from previous iteration with inital value of0
, and the underscore variable (_
) is just the unused variable, it used to be each of the element inside the iterator (and i'm not using it. hence, the_
.)
Here is my code:
pub fn how_many_even(input: Vec<u32>) -> u32 {
input // The input Vec
.iter() // Convert to iterator
.filter(|x| x % 2 == 0) // Filter the even numbers
.fold(0, |acc, _| acc + 1) // Count total filtered elements
// Straight return in the end of line of the function
}
My above program can be interpreted as this pseudocode:
public function how_many_even(input Vec with u32 elements) -> The count of even number in u32 {
1. Prepare the input vector, put it as if it is going to be returned so no semicolons, neither the return statement
a. Convert the input vector to iterator
b. Filter out the even elements
c. Count the rest of existing, filtered elements
2. Return the count value
From the exercise I presented above, it is obvious that Rust's iterators is a versatile tool to edit and return a collections operation in a single line without too much loopings like for
and conditionals like if
. blablabla explain it etc, etc....