I’ve been doing the Weekly
Challenges. The
latest
involved word counting and code validation. (Note that this ends
today.)
Task 1: Max Words
You are given an array of sentences.
Write a script to return the maximum number of words that appear in a single sentence.
Using a crude definition that ignores punctuation, this is easy
enough: split strings on spaces, count words, take maximum.
JavaScript:
function maxwords(a) {
return Math.max(...a.map(x => x.split(" ").length ));
}
Task 2: Validate Coupon
You are given three arrays, @codes, @names and @status.
Write a script to validate codes in the given array.
A code is valid when the following conditions are true:
-
codes[i] is non-empty and consists only of alphanumeric characters
(a-z, A-Z, 0-9) and underscores (_).
-
names[i] is one of the following four categories: 'electronics',
'grocery', 'pharmacy', 'restaurant'.
-
status[i] is true.
Return an array of booleans indicating validity: output[i] is true
if and only if codes[i], names[i] and status[i] are all valid.
The codes validation is most readily done by regexp, where that's
available. names is validated by checking for presence in a set
(though passing around strings is a warning sign that these people
need a lot more expensive tech consultancy). And status is simply a
boolean. In Raku:
sub validatecoupon(@codes, @names, @status) {
my %dep = ["electronics", "grocery", "pharmacy", "restaurant"].Set;
my @out;
for 0 .. @codes.end -> $i {
if (@codes[$i] ~~ /^<[0..9A..Za..z_]>+$/) &&
(%dep{@names[$i]}:exists) &&
@status[$i] {
@out.push(True);
} else {
@out.push(False);
}
}
@out;
}
Full code on
github.