I’ve been doing the Weekly
Challenges. The
latest
involved string-searching integers and bouncing around a keyboard.
(Note that this ends today.)
Task 1: Good Integer
You are given a positive integer, $int
, having 3 or more digits
.
Write a script to return the Good Integer
in the given integer or
-1
if none found.
A good integer is exactly three consecutive matching digits.
So in effect it's a string-searching problem, but not trivially
subject to regexes; if I want to match "000" but not "0000", I also
need to think about starts and ends of the strhing. Or, and this
seemed easier to implement across multiple languages, do a sliding
window.
sub goodinteger($a) {
Several things use the window size, so I'll stick it in a variable.
my $winsize = 3;
Convert the input number to a list of characters.
my @d = $a.comb;
Run a sliding window along it.
for @d.rotor($winsize => 1 - $winsize).kv -> $offset, @cc {
If all the terms in the window are equal, we might have a "good
integer". (If I were making the window size truly variable, I'd use
@list.max == @list.min
.)
if (@cc[0] == @cc[1] && @cc[1] == @cc[2]) {
If we're at the start of the larger list, or the previous character
doesn't match;
if (($offset == 0 || @d[$offset - 1] != @cc[0]) &&
And we're at the end of the list, or the next character doesn't match;
($offset == @d.elems - $winsize || @d[$offset + $winsize]!= @cc[2])) {
Then return the numeric form of the window contents.
return @cc.join('') + 0;
}
}
}
Or return -1.
-1
}
Task 2: Changing Keys
You are given an alphabetic string, $str
, as typed by user.
Write a script to find the number of times user had to change the
key to type the given string. Changing key is defined as using a key
different from the last used key. The shift
and caps lock
keys
won't be counted.
In other words, take the lower-case string and look for letter
changes.
Ruby:
def changingkeys(a)
Define last character and result count.
oc = 'x'
out = 0
Iterate over the lower-case string.
a.downcase.chars.each_with_index do |c, i|
If it's the first character of the string, set the last character, but
don't count it.
if i == 0
oc = c
Otherwise, if it's not the same as the previous character, set the
last character and count it.
elsif c != oc
oc = c
out += 1
end
end
out
end
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.