re: Daily Challenge #29 - Xs and Os VIEW POST

FULL DISCUSSION
 

Very easy (and rather fast) in Perl:

sub xo { local ($_) = @_; tr/xX// == tr/oO// }

It uses the transliteration operator which returns the number of matching characters in scalar context, and numeric comparison imposes scalar context.

The tests:

use Test::More;

ok   xo('ooxx');
ok ! xo('xooxx');
ok   xo("ooxXm");
ok   xo("zpzpzpp");
ok ! xo("zzoo");

done_testing();
 

Perl sorcery 😁. This syntax always turns me inside out hehe. Nice job 👍

 

Sure, but this one is pretty easy to demystify, luckily: tr/set1/set2/ just replaces characters in set1 with those in set2 (positionally), and returns the number of characters replaced/deleted. So in this code, he just compares the number of X's replaced with the number of O's replaced, and includes the lower-case variants too.

The local($_) is just there to let him make the code more brief. $_ is the "default input/pattern-searching space", so its like the default argument that tr will search. But it's also a global, so this lets you make a local copy and set it to be the first argument to the function.

If he didn't do that, it might look like this:

sub xo { my $xos = shift; ($xos =~ tr/xX//) == ($xos =~ tr/oO//) }

So just a bit more verbose.

code of conduct - report abuse