I’ve been doing the Weekly
Challenges. The
latest
involved various string splitting and analysis. (Note that this ends
today.)
Still catching up from holidays, so I did these only in Rust and
Perl.
Task 1: Counter Integers
You are given a string containing only lower case English letters
and digits.
Write a script to replace every non-digit character with a space and
then return all the distinct integers left.
I don't need to do the bit with the spaces.
sub counterintegers($a) {
The numbers are any cluster of digits, split by things that aren't
digits. (split
will occasionally give empty strings.)
my @numbers = grep /./, split /\D+/, $a;
And all the rest is deduplication while retaining the order. I could
have put the values into a new list, but for whimsy I modify the
original list instead. Go through the list…
my $i = 0;
my %seen;
while ($i < scalar @numbers) {
If we've seen this value before, splice it out.
if (exists $seen{$numbers[$i]}) {
splice @numbers, $i, 1;
Otherwise, increment the ilst counter.
} else {
$seen{$numbers[$i]} = 1;
$i++;
}
}
\@numbers;
}
Task 2: Nice String
You are given a string made up of lower and upper case English
letters only.
Write a script to return the longest substring of the give string
which is nice. A string is nice if, for every letter of the alphabet
that the string contains, it appears both in uppercase and
lowercase.
So we'll need to pull out individual characters. In Rust:
fn nicestring(a: &str) -> String {
Turn the string into a list of characters.
let c = a.chars().collect::<Vec<char>>();
let l = c.len();
Start with the longest possible length and then from the start of the
string (because we're going to return the moment we find a match).
for sl in (2..=l).rev() {
for start in 0..=l - sl {
Extract the substring we're working on.
let s = &c[start..start + sl];
Build sets of the upper and lower case characters. For the upper case,
convert to lower case before storing.
let mut lower = HashSet::new();
let mut upper = HashSet::new();
for ch in s {
if ch.is_ascii_lowercase() {
lower.insert(ch.clone());
} else if ch.is_ascii_uppercase() {
let mut cl = ch.clone();
cl.make_ascii_lowercase();
upper.insert(cl);
}
}
If the sets match, we have the longest earliest nice string, so return
it.
if lower == upper {
return s.into_iter().collect();
}
}
}
If we get to the end without doing this, there is no nice substring.
"".to_string()
}
Full code on
github.