Skip to content

Instantly share code, notes, and snippets.

@maufirf
Last active April 22, 2019 10:46
Show Gist options
  • Save maufirf/52c7c9e5a64117fe268c5d5f94114e35 to your computer and use it in GitHub Desktop.
Save maufirf/52c7c9e5a64117fe268c5d5f94114e35 to your computer and use it in GitHub Desktop.
This is the example i've written in discord, just to demonstrate to you how an essay should look like.

Even Counter

The Problem

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 given Vec,
  • Second, Calculate the length of the filtered length
  • Last, return that calculated value.

My Solution

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:

  1. .iter() converts the input Vec into an Iterator
  2. .filter(|x| x % 2 == 0) filters the even value (that satisfies the logic x % 2 == 0 in the closure) for the next calculation as Iterator
  3. .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 of 0, 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

Conclusion

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....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment