Thursday, November 13, 2008

Problem #19

Ok, first thing about solving this is that, since we are going from 1901 - 2000, we dont have to worry about any special leap year conditions, just that it is a leap year every year divisible by four (1904, 1908, 1912, ..., 2000).

I avoided doing this one for a while because I thought it would be hard...heres the code I wrote for it, solved it correctly on my first try.


#include <iostream>
#include <string>

using namespace std;

int daysPerMonth (int, int);
void addOneDay (string&);

int main()
{
string day = "Monday";
int total = 0;

for (unsigned int i = 1901; i < 2001; i++)
for (unsigned int j = 1; j <= 12; j++)
for (unsigned int k = 1; k <= static_cast<unsigned int> (daysPerMonth (j, i)); k++)
{
addOneDay (day);
if (k == 1 && day == "Sunday")
total++;
}

cout << total << endl;

system ("pause");
return 0;
}

// Returns the number of days in that month. If the month is february, it returns
// 29 iff the year is divisible by four
int daysPerMonth (int month, int year)
{
switch (month)
{
case 1:// Jan
return 31;

case 2:// Feb
if (year % 4 == 0)
return 29;
return 28;

case 3:// March
return 31;

case 4:// April
return 30;

case 5:// May
return 31;

case 6:// June
return 30;

case 7:// July
return 31;

case 8:// August
return 31;

case 9:// Sep
return 30;

case 10:// Oct
return 31;

case 11:// Nov
return 30;

case 12:// Dec
return 31;

default:// Error
return 0;

}
}

void addOneDay (string &day)
{
if (day == "Sunday")
day = "Monday";
else if (day == "Monday")
day = "Tuesday";
else if (day == "Tuesday")
day = "Wednesday";
else if (day == "Wednesday")
day = "Thursday";
else if (day == "Thursday")
day = "Friday";
else if (day == "Friday")
day = "Saturday";
else if (day == "Saturday")
day = "Sunday";
}

No comments: