I’ve been doing the Weekly
Challenges. The
latest
involved a progressive average and additive compositions. (Note that
this is open until 25 July 2021.)
TASK #1 › Average of Stream
You are given a stream of numbers, @N
.
Write a script to print the average of the stream at every point.
Bearing in mind that I'm answering these as functions, rather than use
a stream, I take an array and return another array with the sets of
averages (arithmetic means, to be specific). Fairly straightforward:
sub aos(@m) {
my $n=0;
my $t=0;
my @o;
for @m -> $i {
$t+=$i;
$n++;
push @o,floor($t/$n);
}
return @o;
}
PostScript, using a bunch of variables rather than constant stack
furkling. (I haven't used arrays in PostScript before. How quaint,
having to declare a maximum capacity.)
/aos {
/n 0 def
/t 0 def
dup length array /o exch def
{
n add /n exch def
o t
/t t 1 add def
n t div cvi put
} forall
o
} def
Extending my very basic test harness to compare the arrays was harder
work…
TASK #2 › Basketball Points
You are given a score $S
.
You can win basketball points e.g. 1 point, 2 points and 3 points.
Write a script to find out the different ways you can score $S
.
Seems like a call for my standard loop-search pattern. Which meant I
couldn't be bothered to do it in Raku. Here's the Rust.
fn bp (n: u32) -> Vec<Vec<u32>> {
let mut o=vec![];
Some of the other languages make it unreasonably difficult to declare
a list with an empty list as its only member. Not Rust.
let mut p=vec![vec![]];
while p.len() > 0 {
let s=p.pop().unwrap();
Also its sum()
defaults to 0. (Yeah, I could store the sum along
with the list of values that make that sum and it would run a bit
faster, but that would be more work.)
let t: u32=s.iter().sum();
if t==n {
o.push(s);
} else {
let mut mx=n-t;
if mx > 3 {
mx=3;
}
for i in 1..=mx {
let mut q=s.clone();
q.push(i);
p.push(q);
}
}
}
This produces a set of outputs sorted by highest first number, then
highest second number, etc.; so we reverse it to match the input
example.
o.reverse();
return o;
}
The number of entries for increasing $S
matches the Tribonacci
numbers, where each number is the sum of
the three previous values. This might suggest alternative ways of
finding the results; this problem reminded me somewhat of the "Find
Possible Paths" of challenge #117.
Full code on
github.