I've been doing the
Perl Weekly Challenges. This one
dealt with finding letters in words and the mean of circular quantities.
Create a script that accepts two strings, let us call it,
“stones” and “jewels”. It should print the count of
“alphabet” from the string “stones” found in the string
“jewels”. For example, if your stones is “chancellor” and
“jewels” is “chocolate”, then the script should print
“8”. To keep it simple, only A-Z,a-z characters are acceptable.
Also make the comparison case sensitive.
This is pretty straightforward: make a list of the characters
appearing in the first parameter, and check the characters in the
second against it. We also sanitise the parameters to contain only the
allowed characters.
my $a=shift @ARGV or die "need two parameters\n";
$a =~ s/[^A-Za-z]//g;
my %s=map {$_ => 1} split '',$a;
my $b=shift @ARGV or die "need two parameters\n";
$b =~ s/[^A-Za-z]//g;
my $t=0;
map {$t += (exists $s{$_}?1:0)} split '',$b;
print "$t\n";
This is quite similar in Perl6, though the syntax for character
classes is different; and when I did a split, I found I got null start
and end characters, so the final map became a little more fiddly.
my $a=shift @*ARGS or die "need two parameters\n";
$a ~~ s:g/<-[A..Za..z]>//;
my %s=map {$_ => 1}, split '',$a;
my $b=shift @*ARGS or die "need two parameters\n";
$b ~~ s:g/<-[A..Za..z]>//;
my $t=0;
map {if ($_ and %s{$_}:exists) {$t++}}, split '',$b;
say $t;
Create a script that prints mean angles of the given list of
angles in degrees. Please read wiki
page
that explains the formula in details with an example.
We have from that page a formula to implement, so that's easy: convert
the angles to radians, calculate and sum their sines and cosines, take
the mean of each and the two-argument arctangent.
Yes, there's no predefined π in Perl5. Though it's available in
modules and if I were doing this seriously I'd use Math::Trig
.
my $pi=3.1415926535;
my ($s,$c,$n)=(0,0,0);
foreach my $angle (@ARGV) {
my $aa=$angle*$pi/180;
$s+=sin($aa);
$c+=cos($aa);
$n++;
}
my $oa=atan2($s/$n,$c/$n);
print $oa*180/$pi,"\n";
For Perl6, I'd hoped to use the built-in Complex
number type to
implement the other statement of the formula, but it turns out not to
have an argument (phase angle) function, at least in the language
core. So my Perl6 version is basically the same as the Perl5 with
minor syntax changes (and it does have a predefined π).
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.