javadatecalendardayofweek

Project Euler 19: Counting Sundays, Java


I'm using the Calendar API of Java to calculate the total number of sundays which fall on the first day of every month. The Following code gives me 1 extra days for the specified starting date and ending date of date format (Year/Month/Date). 1900/01/01 to 1910/01/01

Input format of the code is :
1<=Testcases<=10
Starting Date
Ending Date

import java.io.*;
import java.util.*;
import java.time.DayOfWeek;
public class ProjectEuler19 {

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner scanner = new Scanner(System.in);
    int testCases = scanner.nextInt();
    do{
     int sundays = 0;
     Calendar c = Calendar.getInstance();
     int monthStart,dateStart,monthEnd,dateEnd;
     int yearStart,yearEnd;
     yearStart = scanner.nextInt();
     monthStart = scanner.nextInt();
     dateStart = scanner.nextInt();
     yearEnd = scanner.nextInt();
     monthEnd = scanner.nextInt();
     dateEnd = scanner.nextInt();
     String[] getDayOfWeek = new String[]{
        "MONDAY",
        "TUESDAY",
        "WEDNESDAY",
        "THURSDAY",
        "FRIDAY",
        "SATURDAY",
        "SUNDAY"
     };
        for(int y = yearStart; y<=yearEnd; y++) {
                for(int m = monthStart; m<=12; m++) {
                        c.set(y,m-1,1);
                        if(String.valueOf(getDayOfWeek[c.get(Calendar.DAY_OF_WEEK)-1]).equals(String.valueOf(DayOfWeek.SUNDAY))) {
                            sundays++;
                        }
                        if(m > monthEnd && y == yearEnd)
                            break;
                }
        }
        System.out.println(sundays);
       testCases--;
    }while(testCases != 0 && testCases>=1 && testCases<=100);

  }
}

And the sample out put is :

2
1900 1 1
1910 1 1
17
2000 1 1
2020 1 1
36

According the calendar the number of sundays between 1900 and 1910 are 18 and the number of sundays between 2000 and 2020 are 35.


Solution

  • You are actually counting the number of Mondays. Calendar.SUNDAY is the first week day constant, and has value 1.

    Why not compare c.get(Calendar.DAY_OF_WEEK) with Calendar.SUNDAY directly?