I’ve been doing the Weekly
Challenges. The
latest
involved a lot of counting. (Note that this ends today.)
Task 1: Odd Character
You are given two strings, $s and $t. The string $t is
generated using the shuffled characters of the string $s with an
additional character.
Write a script to find the additional character in the string $t.
My approach is to build a table of character and count in the first
string, then subtract characters in the second string from it one by
one until I underflow. With Rust I have a Counter class, and with most
of the other languages I at least have the ability to add a default
for a hash value. Ruby:
def oddcharacter(s, t)
Count characters in s…
  ss = Hash.new(0)
  s.chars.each do |c|
    ss[c] += 1
  end
…then iterate the characters of t.
  t.chars.each do |c|
    if ss.has_key?(c) and ss[c] > 0 then
      ss[c] -= 1
    else
      return c
    end
  end
We should never get here (but typed languages need a typed return).
  return "@"
end
Task 2: Most Frequent Word
You are given a paragraph $p and a banned word $w.
Write a script to return the most frequent word that is not banned.
The least portable part here was the split on non-alpha characters
(which in PostScript I had to write from scratch, and a version of
that may end up in the library). But every other language had some way
of doing it. Raku:
sub mostfrequentword($para, $banned) {
    my %words;
    map {%words{$_}++}, $para.comb(/<[A..Za..z]>+/);
    %words{$banned}:delete;
As in task 1, %words now contains a list of words and frequencies.
We find the frequency of the commonest word(s)…
    my $m = %words.values.max;
…filter the list of words to include only those…
    my @v = %words.keys.grep({%words{$_} == $m}).sort;
…and return one of them.
    return @v[0];
}
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.