I’ve been doing the Weekly
Challenges. The
latest
involved poking about with lists. (Note that this ends today.)
Task 1: Equal List
You are given two arrays of strings.
Write a script to return true if the two given array represent the
same strings otherwise false.
In other words, concatenate the arrays into individual strings. Which is
quite straightforward in most languages; here in Rust:
fn equallist(a: Vec<&str>, b: Vec<&str>) -> bool {
a.join("") == b.join("")
}
Task 2: List Division
You are given a list and a non-negative integer.
Write a script to divide the given list into given non-negative
integer equal parts. Return -1 if the integer is more than the size
of the list.
I replaced the "-1" for an invalid answer with an empty list to allow
type consistency.
In Perl:
sub listdivision($a, $n) {
Get the number of items available, and fail if there are too many
parts wanted.
my $al = scalar @{$a};
if ($n > $al) {
return [];
}
Work out an overall division size, stick copies of it in an array, and
increment the earlier ones as needed.
my @divsize = (int ($al / $n)) x $n;
foreach my $i (0 .. ($al % $n) - 1) {
$divsize[$i] += 1;
}
Then take successive slices off the list. (One could do this
destructively with splice but I kept a rolling counter instead.)
my @out;
my $x = 0;
my @a = @{$a};
foreach my $s (@divsize) {
my @r = @a[$x .. $x + $s - 1];
push @out, \@r;
$x += $s;
}
\@out;
}
Full code on
codeberg.