Counting Sundays : Problem 19 Euler Project
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.
JAVA Code
import java.util.*;
import java.io.*;
public class euler19 {
public static void main(String[] args) throws IOException {
int day=1,month=1,year=1900;
int day1=31,month1=12,year1=2000;
DaysCalculation date = new DaysCalculation();
DaysCalculation date1 = new DaysCalculation();
date.setDate(day,month,year);
System.out.println("Number of Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000):"+date.countDays(day1,month1,year1));
}
}
class DaysCalculation {
public void setDate(int d, int m, int y ){
day = d;
month = m;
year = y;
sundayCount = 0;
}
public int countDays(int day1, int month1, int year1 ){
boolean small = false;
int weekDpointer=0;
if (year == year1)
if (month == month1)
if (day < day1)
small = true;
else
small = false;
else if ( month < month1)
small = true;
else
small = false;
else if( year < year1)
small = true;
else
small = false;
if (small == false) {
int td,tm,ty;
td = day;
day = day1;
day1 = td;
tm = month;
month = month1;
month1 = tm;
ty = year;
year = year1;
year1=ty;
}
while (year < year1+1) {
/*if(weekDpointer == 6 && day == 1) {
System.out.println(day+"/"+month+"/"+year+weekDays[weekDpointer]);
sundayCount++;
}*/
day++;
weekDpointer++;
if(weekDpointer >= 7)
weekDpointer %=7;
if (checkLeap(year) == true) {
if (day > ldays[month-1]) {
day = 1;
month ++;
if(weekDpointer == 6 && day == 1 && year != 1900) {
System.out.println(day+"/"+month+"/"+year+"~~"+weekDays[weekDpointer]);
sundayCount++;
System.out.println();
}
if (month > 12) {
month = 1;
year++;
}
}
}
else {
if (day > mdays[month-1]) {
day = 1;
month ++;
if(weekDpointer == 6 && day == 1 && year != 1900) {
System.out.println(day+"/"+month+"/"+year+"~~"+weekDays[weekDpointer]);
sundayCount++;
System.out.println();
}
if (month > 12) {
month = 1;
year++;
}
}
}
} // end of while
return sundayCount;
}
private boolean checkLeap(int year) {
if(year%400==0)
leap=true;
else if (year%100==0)
leap=false;
else if (year%4==0)
leap=true;
else
leap=false;
return leap;
}
private boolean flag;
private static boolean leap;
private int day,month,year;
private int sundayCount;
String[] weekDays ={"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};
}
No comments:
Post a Comment