# RogerBW's Blog

The Weekly Challenge 275: Broken Digits 30 June 2024

I’ve been doing the Weekly Challenges. The latest involved various flavours of string processing. (Note that this ends today.)

Task 1: Broken Keys

You are given a sentence, `\$sentence` and list of broken keys `@keys`.

Write a script to find out how many words can be typed fully.

This smelled like a set intersection problem, so that's the approach I took. In Raku:

``````sub brokenkeys(\$a, @k) {
my \$out = 0;
``````

Build a set of failed keys (lower case).

``````    my %failset = Set(@k.map({\$_.lc}));
``````

For each word,

``````    for \$a.split(" ") -> \$word {
``````

build a set of the characters needed for it.

``````        my %wordset = Set(\$word.lc.comb)
``````

If those sets don't intersecti, there is no broken key in the word, so increment the output counter.

``````        if ((%wordset (&) %failset).elems == 0) {
\$out++;
}
}
return \$out;
}
``````

Task 2: Replace Digits

You are given an alphanumeric string, `\$str`, where each character is either a letter or a digit.

Write a script to replace each digit in the given string with the value of the previous letter plus (digit) places.

If's another of these encoding problems. Fairly straightforward at least in languages that easily let you get a string as a list of characters (which to be fair is basically everything but Lua).

Ruby:

``````def replacedigits(a)
out = ""
prev = 0
``````

Look at each character.

``````  a.chars.each do |c|
out += case c
``````

If it's a digit, add its valud to the previous character code, and convert to a new character for the output.

``````           when '0'..'9'
(prev + c.to_i).chr
``````

Otherwise, store the character code and pass it on.

``````           else
prev = c.ord
c
end
end
out
end
``````

Even PostScript comes out looking basically similar.

``````/replacedigits {
0 dict begin
/prev 0 def
[ exch
s2a {
/c exch def
c 48 ge c 57 le and {
c 48 sub prev add
} {
/prev c def
c
} ifelse
} forall
]
a2s
end
} bind def
``````

Full code on github.