Saturday, January 19, 2013

Problem 19: Counting Sundays


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

Solution:
This is a pretty easy problem, most people will think of using Inbuilt date libraries, but then they are very slow, I solved this by brute force, I think the code is self explanatory.



public class Prob19 {

 
 public static void main(String[] args) 
 {
  int day = 1 ;
  int month = 1;
  int year = 1900;
  String dayName = "Monday";
  int maxDays =0;
  int sundayCounter =0;
  
  while( year < 2001)
  {
   while(month <= 12)
   {
   if(month  == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 )
    maxDays = 31;
   else
   if(month == 2)
   {
   if(leapCounter(year))
   {
    maxDays = 29;
   }
   else
    maxDays = 28;
   }
   else 
    maxDays = 30;
   

   while(day <= maxDays)
   {
    if(day == 1 && dayName.equalsIgnoreCase("sunday") && year > 1900)
     sundayCounter++;
    
    dayName = nextDayReturner(dayName);
    day++;
    
   }
   day  = 1;
   month ++; 
   }
   month = 1;
   year++;
  }
  
System.out.println(sundayCounter);
 }
 static String nextDayReturner(String a)
 {
 a = a.toUpperCase();

  if (a.equalsIgnoreCase("SUNDAY"))
   return "Monday";
  else
  if (a.equalsIgnoreCase("MONDAY"))
   return "Tuesday";
  else
  if (a.equalsIgnoreCase("TUESDAY"))
   return "wednesday";
  else
  if (a.equalsIgnoreCase("WEDNESDAY"))
   return "thursday";
  else
  if (a.equalsIgnoreCase("THURSDAY"))
   return "friday";
  else
  if (a.equalsIgnoreCase("FRIDAY"))
   return "saturday";
  else
   if(a.equalsIgnoreCase("SATURDAY"))
  return "sunday";
   else
    return "Error";
 }

 
 
 

static boolean leapCounter(int year)
{
  if(year%100 == 0)
 {
  if(year % 400 ==0)
   return true;
  else
   return false;
 }else
  if(year % 4 == 0)
   return true;
  else
   return false;
 
 
 
 }
 

}

No comments:

Post a Comment