The weekly challenge 237 - Task 1: Seize The Day
1 #!/usr/bin/perl
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 use strict;
47 use warnings;
48 use DateTime;
49
50
51 seize_the_day(2024, 4, 3, 2);
52 seize_the_day(2025, 10, 2, 4);
53 seize_the_day(2026, 8, 5, 3);
54
55 sub seize_the_day {
56 my ($year, $month, $weekday_of_month, $day_of_week) = @_;
57 print "Input: Year = $year, month = $month, weekday of month = $weekday_of_month, day of week = $day_of_week\n";
58 if($weekday_of_month < 1 or $weekday_of_month > 5) {
59 print "Output: 0\n";
60 return;
61 }
62 my $dt = DateTime->new( year => $year, month => $month, day => 1 );
63 my $days_per_month = {
64 1 => 31, 2 => $dt->is_leap_year ? 29 : 28,
65 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31,
66 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31
67 };
68 my $dow_1st = $dt->day_of_week;
69 my $first_appearance_of_dow = $day_of_week >= $dow_1st ? ( $day_of_week - $dow_1st + 1 ) : ( $day_of_week - $dow_1st + 8);
70 my $nth_appearance_of_dow = $first_appearance_of_dow + ($weekday_of_month-1) * 7;
71 if($nth_appearance_of_dow > $days_per_month->{$month}) {
72 print "Output: 0\n";
73 return;
74 }
75 print "Output: $nth_appearance_of_dow\n";
76 }
77