Wednesday, February 18, 2009

Can the first day of a century fall on a Sunday? Proof by brute force

After reading Straight Dope: Can the first day of a century fall on a Sunday? I threw this code together. Not that I didn't believe their maths/logic, but I thought this would be a really easy thing to brute force with a couple of minutes coding.
        static void Main(string[] args)
        {
            Dictionary<DayOfWeek, int> fallsOnDay = new Dictionary<DayOfWeek, int>();
            foreach (DayOfWeek dow in Enum.GetValues(typeof(DayOfWeek)))
            {
                fallsOnDay.Add(dow, 0);
            }

            for (int year = 100; year < 10000; year += 100)
            {
                DateTime toTest = new DateTime(year, 1, 1);
                fallsOnDay[toTest.DayOfWeek]++;
            }

            foreach (KeyValuePair<DayOfWeek, int> dowCount in fallsOnDay)
            {
                Console.WriteLine(dowCount.Key + " " + dowCount.Value);
            }
            Console.ReadLine();
        }
Output:
Sunday 0
Monday 25
Tuesday 0
Wednesday 25
Thursday 0
Friday 25
Saturday 24
You change line 11 to easily test any other day of the year. For example:
DateTime toTest = new DateTime(year-1, 12, 31); //line 11 changed to test DOW before change in century.
Output:
Sunday 25
Monday 0
Tuesday 25
Wednesday 0
Thursday 25
Friday 24
Saturday 0