I’ve been doing the Weekly
Challenges. The
latest
involved string fiddling and array comparison. (Note that this ends
today.)
Task 1: Group Position
You are given a string of lowercase letters.
Write a script to find the position of all groups in the given
string. Three or more consecutive letters form a group. Return "" if
none found.
Well, I'm using typed languages, so I'm happy to return an empty list
in that last case. This is basically going to be another pass
character by character through a string. Raku:
sub groupposition($a) {
my @mx;
my $lc = 'z';
for $a.comb.kv -> $i, $c {
For the first character, set "most recent character" to something that
isn't this.
if ($i == 0) {
$lc = ($c.ord + 1).chr;
}
If the character hasn't changed, add one to the count of the active
group.
if ($lc eq $c) {
my $mc = @mx.elems;
@mx[$mc - 1][1] += 1;
Otherwise, start a new group, mapping this character to a count of 1.
} else {
@mx.push([$c, 1]);
$lc = $c;
}
}
Then filter the list of groups and format them appropriately (e.g.
['a', 3]
becomes "aaa"
).
my @out;
for @mx -> @ms {
if (@ms[1] >= 3) {
@out.push(@ms[0] x @ms[1]);
}
}
@out;
}
Task 2: Reverse Equals
You are given two arrays of integers, each containing the same
elements as the other.
Write a script to return true if one array can be made to equal the
other by reversing exactly one contiguous subarray.
So basically it's a matter of checking every possible single swap.
JavaScript lacks an array content comparator:
function arrcmp(a, b) {
if (a.length != b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
Then check using a standard traverse through half of the possible
combinations.
(Arguably if the arrays are equal the result should be false
but I'm
going by the examples.)
function reverseequals(a, b) {
if (arrcmp(a, b)) {
return true;
}
for (let i = 0; i < a.length - 1; i++) {
for (let j = i + 1; j < a.length; j++) {
let c = [...a];
for (let x = i; x <= j; x++) {
c[x] = a[j - (x - i)];
}
if (arrcmp(c, b)) {
return true;
}
}
}
return false;
}
Full code on
github.