oddish vs evenish
10.11.2023 2 min readCreate a function that determines whether a number is Oddish or Evenish. A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even. If a number is Oddish, return “Oddish”. Otherwise, return “Evenish”.
crystal
:
# crystal
def oddish_vs_evenish(n : Int32) : String
num = n.to_s.split("").reduce { |a, b| a.to_i + b.to_i }
return num % 2 == 0 ? "Evenish" : "Oddish"
end
nim
:
proc oddishOrEvenish(n: int): string =
let num: int = n.intToStr.toSeq.mapIt(($it).parseInt).foldl(a + b)
if num mod 2 == 0: return "Evenish"
"Oddish"
I didn’t expect this one to be so tedious. Converting a string into a sequence turns each element into a char, and chars don’t have a .parseInt
method defined on them, so we have to convert each char back into a string with the $
operator.
raku
:
sub oddish-vs-evenish(Int $n) {
([+] $n.Str.comb) % 2 == 0 ?? "Evenish" !! "Oddish";
}
Easily the most concise one. Turn the integer into a string, split it into a sequence with .comb
, and use the [+]
prefix operator to reduce it to a single number.
javascript
:
function oddishVsEvenish($n: number) {
const num = $n
.toString()
.split("")
.reduce((acc, curr) => {
acc += parseInt(curr);
return acc;
}, 0);
return num % 2 == 0 ? "Evenish" : "Oddish";
}
Built with Astro and Tailwind 🚀