I’ve been doing the Weekly
Challenges. The
latest
involved string intersections and serial XOR. (Note that this ends today.)
Task 1: Count Common
You are given two array of strings, @str1
and @str2
.
Write a script to return the count of common strings in both arrays.
So basically a set intersection.
And some languages don't have sets, but everything I'm using at least
has hashes/dicts/maps/associative arrays.
Raku:
sub countcommon(@a, @b) {
my %aa = set(@a);
my %bb = set(@b);
(%aa (&) %bb).elems;
}
PostScript (with no local variables, though some of the functions I'm
including do use them):
/countcommon {
toset exch toset set.intersection length
} bind def
Task 2: Decode XOR
You are given an encoded array and an initial integer.
Write a script to find the original array that produced the given encoded array. It was encoded such that encoded[i] = orig[i] XOR orig[i + 1]
.
First output is the initial value, then xor with each in turn. Even
Lua isn't particularly verbose here:
function decodexor(a, init)
local out = { init }
for _, v in ipairs(a) do
table.insert(out, out[#out] ~ v)
end
return out
end
and in PostScript, not only no local variables needed, but all done
with language primitives.
/decodexor {
[ exch
3 -1 roll
{
exch dup 3 -1 roll xor
} forall
]
} bind def
Full code on
github.