I’ve been doing the Weekly
Challenges. The
latest
involved expanding a search space and running a character frequency
test. (Note that this closes today.)
Task 1: Digital Clock
You are given time in the format hh:mm with one missing digit.
Write a script to find the highest digit between 0-9 that makes it valid time.
Wild digits 3 and 4 always give the same result. Wild digits 1 and 2
vary in their result depending on the value of the other digit in the
pair. And that's about it. Kotlin:
fun digitalclock(hhmm: String): Int {
val i = hhmm.indexOf("?")
if (i == 0) {
if (hhmm[1] <= '3') {
return 2;
}
return 1;
} else if (i == 1) {
if (hhmm[0] < '2') {
return 9;
}
return 3;
} else if (i == 3) {
return 5;
} else if (i == 4) {
return 9;
}
return 0;
}
Task 2: Frequency Equalizer
You are given a string made of alphabetic characters only, a-z
.
Write a script to determine whether removing only one character can make the frequency of the remaining characters the same.
To avoid chugging through with trial and error:
-
Take a list of the frequency of occurrence of each character.
-
Sort it numerically.
-
Then the test is true if and only if the first value is the same as
the second-to-last, and one less than the last.
Raku:
sub frequencyequalizer($s) {
my %f;
for $s.comb -> $c {
%f{$c}++;
}
my @v = %f.values.sort;
if (@v[0] == @v[*-2] &&
@v[0] + 1 == @v[*-1]) {
return True;
}
return False;
}
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.