Monthly Calendar with Custom Week Start
Problem statement
Given a year, a month, and a weekday startDay, return that month's calendar as an integer matrix.
Calendar conventions
- For this exercise, assume the proleptic Gregorian calendar: apply the Gregorian rules to every supported year, including years before
1582. - A year is a leap year if it is divisible by
400, or if it is divisible by4and not divisible by100. February has29days in a leap year and28otherwise. April, June, September, and November have30days; the other months have31. - For this exercise, number weekdays as
0 = Sunday,1 = Monday,2 = Tuesday,3 = Wednesday,4 = Thursday,5 = Friday, and6 = Saturday. - The inputs are valid. You may compute weekdays using any correct method.
Calendar layout
- Each row represents one week and contains exactly
7cells. - The leftmost column is
startDay. Each following column advances one weekday, wrapping from Saturday to Sunday. - Place the day numbers from
1through the last day of the month in chronological order, under their corresponding weekdays. - For this exercise, fill cells before day
1and after the month's last day with0. - Return only weeks containing at least one day of the requested month. Do not add an all-zero row.
Progressive task
The calendar exercise builds through these steps:
- Determine the weekday of a date.
- Use the month's length to determine the weekday of its last day.
- Build a month table with weekday
0in the first column. - Generalize the first column to
startDay.
Implement the final generalized calendar. The earlier steps can serve as helpers.
Function
buildMonthlyCalendar(year: int, month: int, startDay: int) → int[][]Examples
Example 1
year = 2024month = 2startDay = 1return = [[0,0,0,1,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,0,0,0]]February 2024 starts on Thursday and has 29 days. The columns are Monday through Sunday, so the first row begins with three zeros. The last row contains 26, 27, 28, 29 followed by three zeros.
Example 2
year = 2021month = 2startDay = 1return = [[1,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]]February 2021 starts on Monday and has 28 days. With Monday as the first column, the month fills exactly four weeks and needs no padding.
Example 3
year = 2026month = 8startDay = 0return = [[0,0,0,0,0,0,1],[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,0,0,0,0,0]]August 2026 starts on Saturday. The first row has six zeros before 1. The final row begins with Sunday 30 and Monday 31, so six rows are required.
Constraints
- For this exercise, assume
1 <= year <= 9999. 1 <= month <= 12.0 <= startDay <= 6.