I've been doing the Perl Weekly
Challenges. This one dealt with
date calculations and exhaustive number searches.
Write a script to list dates for Sunday Christmas between 2019
and 2100. For example, 25 Dec 2022 is Sunday.
I was going to do this straight, but then it seemed like fun to make
it a one-liner. Well, almost.
use Time::Local;
print map {"$_\n"} grep {(gmtime(timegm(0,0,12,25,11,$_)))[6]==0} (2019..2100);
Note that timegm matches gmtime's 0-based month numbering. (And it's a
habit of mine to use timegm, and noon, to minimise the possibility of
time-zone-related confusion, though in this case it shouldn't make any
difference.)
In Perl6 this is just as straightforward:
map {say "$_"}, grep {Date.new($_,12,25).day-of-week==7}, (2019..2100);
I do like Perl6's built-in Date
type, but I'm sure that having to
load it (and all the rest) for every program is the reason startup is
so much slower.
Write a script to print all possible series of 3 numbers, where in
each series at least one of the number is even and sum of the three
numbers is always 12. For example, 3,4,5.
Since this is clearly intended to be a finite list I choose not to
consider negative numbers and non-integers. An optimisation: an even
sum of three integers must by definition contain at least one even
integer, so there's no need to check for it. I optimise further by
generating the numbers in ascending order, so that each combination
will only be displayed once.
my $target=12;
foreach my $a (0..$target) {
foreach my $b ($a..$target) {
my $c=$target-$a-$b;
if ($c>=$b) {
print "$a $b $c\n";
}
}
}
and converting this to Perl6 is just a matter of changing the loop
syntax.
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.