Computing, Education, and Computing Education
RSS

Calendar problem revisited

January 3rd, 2008   Posted by John in assignments, cs1 calendar

Here’s a twist on the classic “What day of the week does a particular date fall on?” problem. A programming solution using the following approach would use several simple lookup tables, probably implemented as arrays, lists, or hash maps. I’ve translated the basic idea that I found here (via reddit) into something more appropriate for programming instructors and students.

The result can be calculated using the following formula:

dayOfWeek = (yearCode + monthCode + day) % 7

The result is an integer in the range 0 to 6, interpreted as follows:

ResultDay
0Saturday
1Sunday
2Monday
3Tuesday
4Wednesday
5Thursday
6Friday

As usual, leap year needs to be accounted for. If the date in question is in a leap year, the result should be decremented by one for the months of January and February.

The month code is a non-intuitive integer as follows:

MonthCode
January1
February4
March4
April0
May2
June5
July0
August3
September6
October1
November4
December6

The year code can also be determined using a lookup table, such as:

YearCode
20055
20066
20070
20082
20093
20104

Or the year code can be computed using the following formula:

yearCode = (centuryCode + twoDigitYear + (twoDigitYear / 4)) % 7

The two digit year value is the last two digits of the year (84 for 1984). The century code follows the 6-4-2-0 pattern below and applies only to dates in the Gregorian calendar.

CenturyCode
1600s6
1700s4
1800s2
1900s0
2000s6
2100s4
2200s2
2300s0

Happy programming.

Post a Comment