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)?

*WARNING: This contains the solution!*

I completely misread this problem when I first started. I think I got too excited and got carried away planning how to solve this before I actually understood what they were asking for. For some reason I was thinking Monday, not Sunday, and also instead of the first of the month I was thinking the first month of the year (January). I eventually realized that I must have read the question wrong and carefully reread it. But I learned a very important life lesson that hopefully I wont have to relearn for a few days at least - know what they are asking before giving an answer.

Moving on, I came up with this interesting solution. Essentially the algorithm only checks every first Sunday of the month and sees if it is the 1st and if so increments the count and moves on. This is pretty basic and I suppose the only cool thing about it is the way I calculate the first Sunday of the month.

#include <iostream>

#include <vector>

using std::cout;

using std::endl;

using std::cin;

using std::vector;

const int NUMBEROFDAYSINWEEK = 7;

int main()

{

//store the number of days in each month

vector<int> months;

months.push_back(31); //January

months.push_back(28); //Feburary

months.push_back(31); //March

months.push_back(30); //April

months.push_back(31); //May

months.push_back(30); //June

months.push_back(31); //July

months.push_back(31); //August

months.push_back(30); //Septemeber

months.push_back(31); //October

months.push_back(30); //November

months.push_back(31); //December

//start date: January 6, 1901 (Sunday)

int year = 1901;

int month = 0;

int firstsunday = 6;

int sundays = 0;

//go month by month checking to see if the first sunday is on the first

while (year < 2001)

{

//if you reached the end of the year then restart to January.

if (month == 12)

{

++year;

month = 0;

}

//check to see if the current first sunday of the month is on the first

if (firstsunday == 1)

++sundays;

//get the number of days in the month (account for possible leap years)

int daysinmonth = months[month] + (month == 1 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));

//calculate the first sunday of the next month

firstsunday = NUMBEROFDAYSINWEEK - ((daysinmonth - firstsunday) % NUMBEROFDAYSINWEEK);

++month;

}

cout << sundays << endl;

}

*saved game*

## No comments:

## Post a Comment