June 2019 Archives

Perl Weekly Challenge 014: Van Eck and the US States

This week, there was more work to be done for some of us: in addition to the standard three challenges, there was one more from Neil Bowers. His suggestion for a challenge had been simplified, so he published the original specification.

Van Eck’s Sequence

Let a0 = 0. Then, for n ≥ 0, if there exists an m < n such that am = an, take the largest such m and set an+1 = n − m; otherwise an+1 = 0.

I didn’t find a non-recursive formula for the sequence. I implemented a solution using an iterator: a subroutine that returns the next element of the sequence on each call.

Let’s start with a test.

Perl Weekly Challenge 013: Last Fridays and Hofstadter Female and Male Sequences

Last Fridays

Write a script to print the date of last Friday of every month of a given year.

To handle dates, I used Time::Piece, a core module since 5.10. It has no method to get the last Friday of a month directly, so I tried a simple trick: get the first day of the next month, subtract one day, and continue to subtract days until we get a Friday.

Time::Piece does all the date maths in seconds. I also used Time::Seconds to get the constant ONE_DAY so I didn’t have to count it myself (60 * 60 * 24, right?)

Perl Weekly Challenge 012: Non-Prime Euclid Numbers and the Common Path

The Smallest Non-Prime Euclid Number

An Euclid number is a number that equals 1 + product of a sequence of primes.

To speed things up, I used an object that caches the sequence of primes discovered so far. The method size returns the length of the sequence of primes; extend_to extends the sequence up to the specified number.

Perl Weekly Challenge 011: Fahrenheit, Celsius, and an Identity Matrix

Compute the Equal Point in the Fahrenheit and Celsius Scales

I used a simple numerical method to find the equal point: Start randomly, move in one direction, if the difference is greater, change the direction, otherwise decrease the step, until there’s no difference.

Perl Weekly Challenge 010: Roman Numerals

Write a script to encode/decode Roman numerals.

This has been solved many times, you can easily google a golfed solution shorter than L characters (for example at code-golf.io).

About E. Choroba

user-pic I blog about Perl.