Sunday the 1st
Published on Tuesday, July 26, 2011Not much thought went into this solution. Problem 19 asks the reader to find the number of months that began with Sunday during the 20th century. There's probably a clever way to find this out, but I wrote a program that ran through every month of the century, offsetting the day of the week by 3 for 31-day months, 2 for 30-day months, and 1 for February during leap years. Before offsetting, the program checked to see if the dayOfWeek
was set to zero (Sunday) and, if so, augmented numOfSundaysOnFirstOfMonth
by one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Problem019
{
class Program
{
static void Main(string[] args)
{
int numOfSundaysOnFirstOfMonth = 0;
int dayOfWeek = 2; // Tuesday
for (int year = 1901; year < 2001; year++)
{
for (int month = 1; month <= 12; month++)
{
if (dayOfWeek == 0)
numOfSundaysOnFirstOfMonth++;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dayOfWeek = (dayOfWeek + 31) % 7;
break;
case 4:
case 6:
case 9:
case 11:
dayOfWeek = (dayOfWeek + 30) % 7;
break;
case 2:
if (year % 4 == 0 && year % 400 != 0)
dayOfWeek = (dayOfWeek + 29) % 7;
break;
}
}
}
Console.WriteLine("{0} months began on Sunday during the 20th century",numOfSundaysOnFirstOfMonth);
}
}
}