I’ve been doing the Weekly
Challenges. The
latest
involved list filtering and sequence generation. (Note that this ends
today.)
Task 1: Special Numbers
You are given an array of integers, @ints.
Write a script to find the sum of the squares of all special
elements of the given array.
An element $int[i] of @ints is called special if i divides n, i.e. n
% i == 0. Where n is the length of the given array. Also the array
is 1-indexed for the task.
Well, there's a fairly obvious way to do this iteratively, as seen
here in Raku:
sub specialnumbers(@a) {
my $t = 0;
for (0 .. @a.end) -> $i {
if (@a.elems % ($i + 1) == 0) {
$t += @a[$i] * @a[$i];
}
}
return $t;
}
However, I prefer a purely functional approach. I wasn't able to
wrangle Kotlin or Scala into doing this, though I think they can; but
it was fairly straightforward in Rust:
fn specialnumbers(a: Vec<u32>) -> u32 {
a.iter()
.enumerate()
.filter(|(i, _n)| a.len() % (i + 1) == 0)
.map(|(_i, n)| n * n)
.sum()
}
and the equivalent in PostScript with my extensions:
/specialnumbers {
0 dict begin
dup /l exch length def
enumerate.array
{ 0 get 1 add l exch mod 0 eq } filter
{ 1 get dup mul } map
{ add } reduce
end
} bind def
Task 2: Unique Sum Zero
You are given an integer, $n
.
Write a script to find an array containing $n
unique integers such
that they add up to zero.
Obviously there are infinite possible solutions to this, but I chose a
simple one
(1, 2, 3, ..., -sum(1..n-1))
with the last term calculated using the identity:
sum(1..n) = n * (n + 1) / 2
And therefore, in JavaScript:
function uniquesumzero(n) {
if (n == 1) {
return [0];
}
let p = Array(n - 1).fill().map((element, index) => index + 1);
p.push(-n * (n-1) / 2);
return p;
}
Some other approaches might have been:
(1, -1, 2, -2, ... )
with a zero at the end if $n
is odd; or
(1, 2, 4, 8, ... -(2^(n-1) - 1))
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.