I’ve been doing the Weekly
Challenges. The
latest
involved string and set manipulation. (Note that this ends today.)
Task 1: Broken Keyboard
You are given a string containing English letters only and also you
are given broken keys.
Write a script to return the total words in the given sentence can
be typed completely.
This smells to me like a set intersection, so obviously it's easier in
languages that have sets. Crystal:
def brokenkeyboard(a, b)
Turn the key list into a set of characters.
bk = Set.new(b.map{|x| x.downcase.chars[0]})
Count the possible words.
ct = 0
For each possible word,
a.downcase.split(" ").each do |w|
build a set of needed characters.
nk = Set.new(w.chars)
If that does not intersect the set of broken keys,
if (bk & nk).size == 0
Score it as a word we can type.
ct += 1
end
end
ct
end
The other languages work similarly; where sets aren't available, I use
an associative array with character keys and boolean-true values.
Task 2: Reverse Prefix
You are given a string, $str
and a character in the given string,
$char
.
Write a script to reverse the prefix upto the first occurrence of
the given $char in the given string $str and return the new string.
Reversing strings is one of those things that never seems to be fun.
Mostly I chopped the string into a character array; even languages
that treat strings as arrays of character anyway (e.g. Python) often
don't let you write to them. Anyway, in Raku
sub reverseprefix($a, $f) {
Build the arrya.
my @c = $a.comb;
Find the anchor.
my $p = index($a, $f);
If it was found,
with ($p) {
Buld the sub-array and reverse it.
my @jr = @c[0 .. $p];
@jr = @jr.reverse;
Copy it back into the original.
splice @c, 0, $p + 1, @jr;
}
Join the array back into a string.
join('', @c);
}
Full code on
github.