adamcrussell

Perl Weekly Challenge 019

For this week's challenges I was able to re-use some code from a previous week. The "day of week" calculation using the Sakamoto method from Week 13 got to be re-used for Part 1. 

Part 1

Problem Statement

Write a script to display months from the year 1900 to 2019 where you find five weekends.

Solution

Sample Run

$ perl perl5/ch-1.pl
1901 March
1902 August
1903 May
1904 January
1904 July
1905 December
1907 March
.
.
.
2016 July
2017 December
2019 March

Discussion

The code above is cropped to fit better here. What is missing are the use constant declarations for the months and days of the week. I like using named constants for these sorts of values, it makes the code much more readable I feel. The only downside is that it makes the code slightly longer. The problem statement defined a weekend as Friday, Saturday, and Sunday so the essence of my approach was to iterate over every day of the month and save those three days to an array references stored in a hash keyed by year and month. When complete if the number of days in the array reference is divisible by five then we know that month has five complete weekends. Any month found this way is printed out.

Part 2

Problem Statement

Write a script that can wrap a given paragraph at a specified column using the greedy algorithm approach.

Sample Run

$ perl perl5/ch-2.pl
A simple way to do word wrapping is to use a greedy algorithm that puts as many words on a line as possible, then moving on to the next line to do the same until there are no more words left to place. This method is used by many modern word processors, such as OpenOffice.org Writer and Microsoft Word. This algorithm always uses the minimum possible number of lines but may lead to lines of widely varying lengths.

Discussion

The line length is set as a constant and the text to be wrapped is kept in the data section. The text itself is the definition of the greedy algorithm approach from wikipedia. Words are put in an array and printed out by The Price is Right rules: the sum of words on the line can be lesser than or equal to, but not more than, the maximum line length.

Comments for this post were locked by the author