DEV Community

Discussion on: Daily Challenge #81 - Even or Odd

Collapse
 
diegolago profile image
Diego Lago

D version, assuming that the string of numbers is a string with integers separated by spaces:

import std.stdio : writeln;
import std.array : split;
import std.conv : to;
import std.algorithm.iteration : map, sum;

string compareEvenOdd(string numbers) {
    auto result = numbers
        .split()
        .map!(a => to!int(a))
        .map!(a => a % 2 == 0 ? a : -a)
        .sum();
    return result < 0 ? "Odd is greater than Even" :
          (result > 0 ? "Even is greater than Odd" :
                        "Even and Odd are the same");
}    

void main() {
    compareEvenOdd("1 2 3 4 5 6 7 8 9").writeln();
    compareEvenOdd("1 3 6 98 35").writeln();
    compareEvenOdd("1 1 2 1 1 2 1 1 2").writeln();
}

Output:

Odd is greater than Even
Even is greater than Odd
Even and Odd are the same