I’ve been doing the Perl Weekly
Challenges. The
latest
involved bad things and triangular numbers. (Note that this is open
until 18 April 2021.)
TASK #1 › Locate Memory
Write a script to declare a variable or constant and print its
location in the memory.
Bad! Dirty! No! There is no good reason to do this in a high-level
language: if it seems to solve your problem, you are solving the
wrong problem and it will come back and bite you later. (With very
minor exceptions when you're building the language and trying to
work out what's going on.)
Therefore I only did it in Perl and Raku:
printf('0x%x',0+\$foo);
and
say sprintf('0x%x',$foo.WHERE);
though I will point out that even the documentation for the latter
method explicitly states:
Please note that in the Rakudo implementation of Raku, and possibly
other implementations, the memory location of an object is NOT fixed
for the lifetime of the object. So it has limited use for
applications, and is intended as a debugging tool only.
Don't do this, folks.
TASK #2 › Bell Numbers
Write a script to display top 10 Bell Numbers. Please refer to
wikipedia page for more
informations.
Bell numbers were named, though not discovered, by Eric Temple Bell –
probably no relation though he was from the same part of Scotland as
some of my wife's ancestors.
I took "top 10" to mean "first 10". There's a pretty straightforward
row by row calculation method described on that page, so that was what
I did.
sub bell {
my $count=shift;
my @a=([1]);
foreach my $row (1..$count-1) {
my @b=$a[-1][-1];
foreach my $col (1..$row) {
push @b,$b[$col-1]+$a[-1][$col-1];
}
push @a,\@b;
}
return [map {$_->[0]} @a];
}
and the others are similar; Raku wants you to use *-1
to mean the
last of something, and I can sort of see their point, though using the
asterisk feels odd. Python and Ruby are happy with -1.
Oddly, in Rust I wasn't able to get the final map
to work so I ended
up building an output vector. (Also, [-1]
becomes .last().unwrap()
and futzes about with references and pointers. Arg. Which is why I
ended up explicitly declaring the types of my array contents.)
fn bell(count: usize) -> Vec<u64> {
let mut a: Vec<Vec<u64>>=vec![vec![1]];
for row in 1..count {
let mut b: Vec<u64>=vec![*a.last().unwrap().last().unwrap()];
for col in 1..=row {
b.push(b[col-1]+&a.last().unwrap()[col-1]);
}
a.push(b);
}
let mut out: Vec<u64>=vec![];
for i in a {
out.push(i[0]);
}
return out;
}
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.