The Friday Fragment

Published on 31 December 2010
This post thumbnail

It's Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week's Fragment

If you coded last week's fragment under Linux, you could check your results by running cal month year. The unix cal utility formats calendars based on the current date or a given date. So let's continue our new year's programming along those lines:

Write code to print out a month's calendar given a month and year.

To play along, post the code for the solution as a comment or send it via email. You can built atop last week's solution to determine the starting day of week. There are likely many implementations already available (including C code for the unix utility), but this is a good opportunity to try new languages or techniques.

Last Week's Fragment - Solution

With our round of game programming, our code solutions had grown a bit larger than mere fragments. So last week's puzzle returned to something short and sweet, as Friday Fragments marked Christmas Eve and New Year's Eve:

Write code to calculate the day of week (Sunday through Saturday) for a given date. Remember to account for leap years.

This is something of a classic math puzzle, and it's not too tough to do the calculation mentally. Many languages have a library function for this, but calling that would be cheating. Perhaps the simplest approach is to implement Zeller's Congruence in the language of your choice, overcoming numeric conversions. I coded it in newly-explored Gosu:

   uses java.lang.Math
   var month=12;   var day=31;    var year=2011;  // Your date here
   var dayNames = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }

   // Shift the year to start in March, split the year components:
   if (month<3) { month += 10; year--; }
   else         { month -= 2; }
   var shortYear = year % 100
   var century = (year / 100)

   // Zeller's: W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7
   var dayOfWeek = ((day +
                      Math.floor((2.6 * month) - 0.2) - (2 * century) +
                      shortYear + Math.floor(shortYear/4) + Math.floor(century/4)) % 7) as int

Have a happy 1-1-11!