adamcrussell

Perl Weekly Challenge 026

Part 1

Sample Run

$ perl perl5/ch-1.pl chancellor chocolate
8

What I Did

First off, I have to say that I re-used some code from Part 2 of Challenge 004. In that challenge I did the same basic technique used here where for each letter in the alphabet we are searching from (the "stones" string) a closure is created which removes a specific letter from the target (the "jewels"). 

Looking at the code you'll see that all the closures are stored in an array and called in a loop. At each iteration of the loop the "jewels" are reviewed and the number of removed "stones" are added to $count. At the end of the loop $count will contain the total number of "stones" found in "jewels" and is returned.

Part 2

Sample Run

$ perl perl5/ch-2.pl 10 20 30
20

$ perl perl5/ch-2.pl 355 15 5
5

What I Did

When working with angles one of the main causes of frustration is the use of degrees and radians. Intuitively most people think in degrees but almost all trigonometry functions provided by standard libraries expect arguments passed as radians. Because this is a challenge I choose, as usual, to avoid using any CPAN modules. Due to this I have defined my own deg2rad and rad2deg functions. The value of PI is held in a constant defined using a classic identity with atan2.

The list of angles is provided on the command line in degrees. These are converted to radians and the converted angles are passed to compute_mean_angle() which implements the computation described in [1]. I generally dislike the overuse of map in Perl code but here it seems to fit very well and the code has an overall cleaner appearance because of it, I believe.

The mean angle is returned, in radians, and converted to degrees and printed.

References

[1] https://en.wikipedia.org/wiki/Mean_of_circular_quantities


Comments for this post were locked by the author