I’ve been doing the Weekly
Challenges. The
latest
involved list counting. (Note that this ends today.)
Task 1: Unique Number
You are given an array of integers, @ints
, where every elements
appears more than once except one element.
Write a script to find the one element that appears exactly one time.
Which means "stuff the list into a hash of entries and counts", first.
PostScript:
/uniquenumber {
0 dict begin
Build the counter.
/c 0 dict def
{
/n exch def
c n c n 0 dget 1 add put
} forall
Then search the hash to find the key where the value is 1.
-1
c keys {
/n exch def
c n 0 dget 1 eq {
pop n
exit
} if
} forall
end
} bind def
Task 2: Digit Count Value
You are given an array of positive integers, @ints
.
Write a script to return true
if for every index i
in the range
0 ≤ i < size of array
, the digit i
occurs exactly the
$ints[$i]
times in the given array otherwise return false
.
Which wants another counter.
Raku:
sub digitcountvalue(@a) {
Set up the counter.
my %c;
@a.map({%c{$_}++});
For each index value:
for 0 .. @a.end -> $ix {
If the value at that point in the list doesn't equal the count of that
value, bail out with false
.
if (@a[$ix] != (%c{$ix} || 0)) {
return False;
}
}
If everything passed, return true
.
return True;
}
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.