Yesterday was Leap Day – 29 February – a day which only comes along once every four years. Or so. It’s actually more complicated than that which we’ll get to in a moment. What this means for me is, you guessed it, programming projects.
I’ve used the old “is this year a leap year” for decision statements for years. Dan Anderson tweeted out a very clear and helpful flowchart for this task.
That one is going up on my bulletin board and will probably show up in a lecture as well. Great stuff.
But there is more. Doug Peterson has a blog post about leap year and counting days. (February 29) In the post he lays out a set of programming projects of increasing complexity. He starts with counting between two days in the same month and works up to calculating the number of days between any two days crossing century boundaries. Yeah that one is going to be some work. Doug and I had a twitter conversation and I started working on this problem in preparation for assigning it to my students one of these days.
One reason one does this is to learn what problems students might run into. Another is to see what shortcuts they might find. In this case I found several starting with the MonthCalendar object in .NET. That takes care of pretty much the whole validating the dates issue.
Next it turns out that there is a DateTime object that allows for subtraction and returns a value of type TimeSpan. It’s a simple matter to get the time span in days from that object. So rather than a very complicated set of methods with decision statements and data checking and worrying about leap years the whole project can be completed in three statements. Possibly fewer if you don’t care about readability.
I’m going to have to be very careful about how I specify this project if I want students to do things the “hard way.”