The Weekly Challenge 013

Last Friday of the Month and Mutually Recursive Methods

Solutions on GitHub

Task 1: Last Friday of the Month

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

Example Output (Year 2019)

2019/01/25 2019/02/22 2019/03/29 2019/04/26 2019/05/31 2019/06/28 2019/07/26 2019/08/30 2019/09/27 2019/10/25 2019/11/29 2019/12/27

Logic

For each month from 1 to 12, start with the last day of the month (which can be 28, 29, 30, or 31). Walk backward day-by-day until a day is found that corresponds to a Friday. In Python, this can be computed directly using the calendar module by finding the last day and calculating the offset to the previous Friday. In Perl, the Date::Calc module's check_date and Day_of_Week functions allow iterating and validating dates.

Perl Solution

ch-1.pl

use Date::Calc qw/check_date Day_of_Week/; my $year = shift // die 'No year passed'; for my $month (1..12) { my $day = 31; while ($day) { $day-- until check_date($year, $month, $day); if (Day_of_Week($year, $month, $day) == 5) { say $year.'/'.$month.'/'.$day; $day = 1; } $day--; } }

Python Solution

ch-1.py

import calendar def get_last_friday_of_month(year: int, month: int) -> str: last_day = calendar.monthrange(year, month)[1] last_day_weekday = calendar.weekday(year, month, last_day) days_to_friday = (last_day_weekday - 4) % 7 last_friday_day = last_day - days_to_friday return f"{year}/{month:02d}/{last_friday_day:02d}" def get_all_last_fridays(year: int) -> list[str]: return [get_last_friday_of_month(year, month) for month in range(1, 13)]

Task 2: Mutually Recursive Methods

Demonstrate mutually recursive methods by generating the Hofstadter Female and Male sequences.

Example Output (n=10)

Female: 1, 1, 2, 2, 3, 3, 4, 5, 5, 6 Male: 0, 0, 1, 2, 2, 3, 4, 4, 5, 6

Logic

Hofstadter Female ($F$) and Male ($M$) sequences are mutually recursive sequences defined as: $$F(0) = 1, \quad M(0) = 0$$ $$F(n) = n - M(F(n-1)), \quad n > 0$$ $$M(n) = n - F(M(n-1)), \quad n > 0$$ To prevent exponential runtime, we employ caching (memoization) for intermediate calculations in both functions.

Perl Solution

ch-2.pl

my %f_cache = (0 => 1); my %m_cache = (0 => 0); sub f { my $n = shift; return $f_cache{$n} if exists $f_cache{$n}; my $result = $n - m(f($n - 1)); $f_cache{$n} = $result; return $result; } sub m { my $n = shift; return $m_cache{$n} if exists $m_cache{$n}; my $result = $n - f(m($n - 1)); $m_cache{$n} = $result; return $result; }

Python Solution

ch-2.py

_f_cache: dict[int, int] = {0: 1} _m_cache: dict[int, int] = {0: 0} def female(n: int) -> int: if n in _f_cache: return _f_cache[n] result = n - male(female(n - 1)) _f_cache[n] = result return result def male(n: int) -> int: if n in _m_cache: return _m_cache[n] result = n - female(male(n - 1)) _m_cache[n] = result return result