Reputation: 557
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 :
My following logic gives me 173 Sundays , whereas there are 171 Sundays !! Where are the extra 2 days came from ?
public static void main(String args[]) {
Date startDate = new Date(1901, Calendar.JANUARY, 01);
Date endDate = new Date(2000, Calendar.DECEMBER, 31);
checkSundays(startDate, endDate);
}
private static void checkSundays(Date start, Date end) {
int dayNum;
Calendar startDate = Calendar.getInstance();
startDate.setTime(start);
System.out.println(startDate.getTime());
Calendar endDate = Calendar.getInstance();
endDate.setTime(end);
System.out.println(endDate.getTime());
int count = 0;
while (startDate.before(endDate)) {
for (int i = 1; i < 13; i++) {
dayNum = startDate.get(Calendar.DAY_OF_WEEK);
if (dayNum == 1) {
count++;
}
System.out.println(startDate.getTime());
startDate.add(Calendar.MONTH, 1);
}
System.out.println("Count " + count);
}
}
Upvotes: 1
Views: 1280
Reputation: 667
You can use probability and do this with just a calculator.
There's 100 years in a century, and every year, there are 12 first days of the months. Divide that by 7 and you have your answer.
It's cheap, but it works.
Upvotes: 0
Reputation: 240948
Your following code uses deprecated constructor of Date
Date startDate = new Date(1901, Calendar.JANUARY, 01);
System.out.println(startDate);
which is not proper, it prints
Thu Jan 01 00:00:00 IST 3801
So use Calendar
to construct Date
,
Calendar startDateCal = createDateInstance(0,1901,1)
Calendar endDateCal = createDateInstance(11,2000,13)
and a Factory method
public static Date createDateInstance(int month, int year, int date){
Calendar cal= Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DATE, date);
return cal.getTime();
}
Upvotes: 3