Monday, January 14, 2008

Project Euler - Problem 19 - JodaTime Rocks

Problem 19

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

This really feels like cheating, but the very simplest way I immediately thought to solve this was using Joda Time.

Joda Time is a wonderfully written Java library, that replaces the need for the both inept and ugly mess that is java.util.Date and java.util.Calendar. Joda Time is so good that it is the basis on which the new Java 7 Date and Time API will be built (see here).

Here's my solution in the typically oh so long winded Java:
DateTime date = new DateTime(1901, 1, 1, 0, 0, 0, 0);
DateTime end = new DateTime(2000, 12, 30, 0, 0, 0, 0);

int numberOfSundays = 0;

while (date.isBefore(end)) {
if (date.getDayOfWeek() == DateTimeConstants.SUNDAY) {
numberOfSundays++;
}
date = date.plusMonths(1);
}
Short, simple, expressive. Thanks Joda Time.