loading...

Discussion on: Daily Challenge #81 - Even or Odd

Collapse
idanarye profile image
Idan Arye

Rust

Rather than keeping two sums, we can negate one of the options (I chose to negate the evens) and compare the sum to 0:

use std::cmp::Ordering;

fn compare_even_to_odd(numbers: impl Iterator<Item = i64>) -> String {
    let comparison = numbers.map(|number| if number % 2 == 0 {
            - number
        } else {
            number
        }
    ).sum::<i64>().cmp(&0);
    match comparison {
        Ordering::Less => "Even is greater than Odd".to_owned(),
        Ordering::Equal => "Even and Odd are the same".to_owned(),
        Ordering::Greater => "Odd is greater than Even".to_owned(),
    }
}
fn main() {
    println!("{}", compare_even_to_odd((&[1, 3, 4]).iter().map(|a| (*a))));
}