DEV Community

loading...

Discussion on: Daily Challenge #29 - Xs and Os

Collapse
willsmart profile image
willsmart • Edited

How about a reduce to keep it in one loop? (JS)

XO = str => 
  [...str].reduce(
    (acc, c) => acc + (c == 'x' || c == 'X') - (c == 'o' || c == 'O'),
    0
  ) == 0;

// Check it
["ooxx","xooxx","ooxXm","zpzpzpp","zzoo"].map(s =>
  `${s} => ${XO(s)}`
).join('\n');
/* ^
"ooxx => true
xooxx => false
ooxXm => true
zpzpzpp => true
zzoo => false"
*/
Collapse
nishu1343 profile image
nishu1343

Bro, nice solution .cud u explain me what is going inside the reduce. And im not able to reproduce it.

Collapse
willsmart profile image
willsmart • Edited

It's working for me in chrome just now. Try wrapping the output line in a console.log if you're outside a REPL

In the reduce acc is the accumulator, keeping a sum of values as they come up. The reduce returns the sum at the end.
Each c is a character from the string (...str is an array of the chars from str)
c == 'x' || c == 'X' is obv a boolean. The code uses the fact that in JS Number(true) == 1 and Number(false) == 0, so it's a shorter way of saying:

XO = str => 
  [...str].reduce(
    (acc, c) => acc + (c == 'x' || c == 'X' ? 1 : 0) - (c == 'o' || c == 'O' ? 1 : 0),
    0
  ) == 0;

So each x adds one to the sum, and each o subtracts one. If the sum is zero there are the same number of x's as o's

Thread Thread
nishu1343 profile image
nishu1343

Cool.its working😃

Collapse
thepeoplesbourgeois profile image
Josh

Oh, nice! I wouldn't have thought to use the array spread syntax to get the array of characters. 🎩✨

Forem Open with the Forem app