# Duncan's blog

## November 5, 2008

### Project Euler: problem 19

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , ,

This was a problem I’d initially passed over as I thought it looked a bit tricky, then when I came back to it I realised it wasn’t that hard at all.

Problem 19:

You are given the following information, but you may prefer to do some research for yourself.

• 1 Jan 1900 was a Monday.
• Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
• A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

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

The reason it didn’t turn out that hard was because Coldfusion has many useful date functions built in. In fact, I started writing my own IsLeapYear() function before realising that was one that already existed.

```<cfset sum = 0>

<cfset start = CreateDate(1901, 1, 1)>
<cfset end = CreateDate(2000, 12, 31)>

<cfloop index="i" from="#start#" to="#end#">
<cfif DayOfWeek(i) EQ 1 AND FirstDayOfMonth(i) EQ DayOfYear(i)>
<cfset sum = sum + 1>
</cfif>
</cfloop>

<cfoutput>#sum#</cfoutput>
```

Looping through dates like this isn’t something I do often. In this loop, i is an ordinal value, e.g. 365, 366, 367 etc, which corresponds to dates from 1st January 1900 onwards it seems.

DayOfWeek returns a value from 1 to 7, where 1 equals Sunday. If you ever do any calendar work, this is a useful function. Its only problem is if you’re trying to do a calendar where Monday is the first day of the week instead of Sunday; it then becomes a bit tricky. I find that a bit of a bug-bear, because of course Monday is the first day of the week, as any fule knoe (and there’s an ISO standard that says the same). Ideally DayOfWeek could take an optional attribute to define whether Monday or Sunday is the desired first day. Or even have an LSDayOfWeek.

FirstDayOfMonth is one of those functions I’ve maybe never used, or only very rarely. If you give it a date, it’ll tell you what day of the year (1-365/366) was the first day of that month. So by comparing FirstDayOfMonth(i) to DayOfYear(i), if they’re the same then that day was indeed the first of a month.