I’ve been doing the Weekly
Challenges. The
latest
involved counters and numerical analysis. (Note that this ends today.)
Task 1: Single Common Word
You are given two array of strings.
Write a script to return the number of strings that appear exactly
once in each of the two given arrays. String comparison is case
sensitive.
So what I want for this is a counter, i.e. a hash in which each key is
a string in the array and each value is the number of times that
string occurs. In Perl.
sub singlecommonword($a, $b) {
my %ac;
map {$ac{$_} += 1} @{$a};
my %bc;
map {$bc{$_} += 1} @{$b};
Then I compare the two.
my $total = 0;
For each word in the A list:
while (my ($w, $ca) = each %ac) {
If it occurs once, and it's in the B list, and it occurs once there,
count it.
if ($ca == 1 && exists $bc{$w} && $bc{$w} == 1) {
$total += 1;
}
}
$total;
}
Task 2: Find K-Beauty
You are given a number and a digit (k).
Write a script to find the K-Beauty of the given number. The
K-Beauty of an integer number is defined as the number of substrings
of given number when it is read as a string has length of 'k' and is
a divisor of given number.
I don't like treating numbers as strings, but…
Scala:
def findkbeauty(a: Int, n: Int): Int = {
var total = 0
Get a list of characters in the input number.
val c = a.toString.toList
Iterate across the substrings of the right length.
for (t <- c.sliding(n)) {
Get the numerical value of that substring.
val tn = t.mkString("").toInt
If it's a multiple, score it.
if (a % tn == 0) {
total += 1
}
}
total
}
Full code on
codeberg.