I’ve been doing the Weekly
Challenges. The
latest
involved character repetition and a basic string parse. (Note that
this ends today.)
Task 1: Twice Appearance
You are given a string, $str
, containing lowercase English letters
only.
Write a script to print the first letter that appears twice.
The way to do this that seemed most obvioius to me was to iterate with
a set: if the character is already in the set, return it, otherwise
put it in the set.
One could add error handling in the case that no character is
repeated, but that's outside the problem scope.
sub twiceappearance($a) {
Construct the set.
my %m = SetHash.new;
For each character,
for $a.comb -> $c {
If it's in the set,
if (%m{$c}:exists) {
Return it.
return $c
}
Otherwise add it to the set.
%m{$c}++;
}
We should never get here but in languages with return types this is needed.
return 'x';
}
Task 2: Count Asterisks
You are given a string, $str
, where every two consecutive vertical
bars are grouped into a pair
.
Write a script to return the number of asterisks, *
, excluding any
between each pair of vertical bars.
One could probably do this with proper parsing, but the quick way
seemed to be to iterate characters again: a |
toggles the active
flag (which begins as true
), and a *
adds to the count if the
active flag is true
.
Rust:
fn countasterisks(a: &str) -> u32 {
Set output value and active flag.
let mut out = 0;
let mut active = true;
For each character,
for c in a.chars() {
match c {
If it's |
, toggle active flag.
'|' => active = !active,
If it's *
and active is true, add one to the output.
'*' => {
if active {
out += 1
}
}
_ => {}
}
}
out
}
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.