Monday, September 14, 2009

Project Euler Problem 19

I've been solving these in order of ascending difficulty, but when sorting by problem number, I noticed that Problem 19 was the most difficult (according to the number of people who've solved it) within the first 20 problems. I was surprised because I thought this would be really easy, and it was. The code pasted below took me only 10 minutes to write, and was correct on the first try.


/*
* Problem 19
* 14 June 2002
*
* How many Sundays fell on the first of the month during the twentieth century
* (1 Jan 1901 to 31 Dec 2000)?
*/

import org.joda.time.DateTime;

public class PE0019
{
public static void main(String[] args)
{
int numberOfSundays = 0;
int monthCounter = 0;

DateTime startDate = new DateTime(1901, 1, 1, 0, 0, 0, 0);
DateTime endDate = new DateTime(2000, 12, 31, 0, 0, 0, 0);

DateTime currentDate = startDate;

while (currentDate.getMillis() < endDate.getMillis())
{
currentDate = startDate.plusMonths(monthCounter++);
if (currentDate.getDayOfWeek() == 7)
numberOfSundays++;
}

System.out.println(numberOfSundays);
}
}

No comments:

Post a Comment