Calendar problem revisited
January 3rd, 2008 Posted by John in assignments, cs1
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:
| Result | Day |
|---|---|
| 0 | Saturday |
| 1 | Sunday |
| 2 | Monday |
| 3 | Tuesday |
| 4 | Wednesday |
| 5 | Thursday |
| 6 | Friday |
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:
| Month | Code |
|---|---|
| January | 1 |
| February | 4 |
| March | 4 |
| April | 0 |
| May | 2 |
| June | 5 |
| July | 0 |
| August | 3 |
| September | 6 |
| October | 1 |
| November | 4 |
| December | 6 |
The year code can also be determined using a lookup table, such as:
| Year | Code |
|---|---|
| 2005 | 5 |
| 2006 | 6 |
| 2007 | 0 |
| 2008 | 2 |
| 2009 | 3 |
| 2010 | 4 |
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.
| Century | Code |
|---|---|
| 1600s | 6 |
| 1700s | 4 |
| 1800s | 2 |
| 1900s | 0 |
| 2000s | 6 |
| 2100s | 4 |
| 2200s | 2 |
| 2300s | 0 |
Happy programming.