简体   繁体   中英

I can't figure out why my logic is wrong for USACO Friday the 13th?

I use 1 to refer to monday, 2 to refer to tuesday etc.

When I give a years value of 1, it returns 1 2 1 3 1 2 2 , whereas according to the USACO grader, it should return 2 1 1 3 1 2 2 .

This sequence means that in the span of a year, 2 saturdays have a date of 13th, 1 sunday has a date of 13th etc.

    import java.io.*;
    import java.util.*;

    class friday { 
      static boolean isLeapYear(int year) {
        if(year%4==0){
          if(!(year%100==0))
            return true;
          else if(year % 400 == 0)
            return true;
          return false;
        }
        return false;
      }
      public static void main (String [] args) throws IOException {
        // Use BufferedReader rather than RandomAccessFile; it's much faster
        BufferedReader f = new BufferedReader(new FileReader("friday.in")); // input file name goes above
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("friday.out")));
        int n = Integer.parseInt(f.readLine()); //number of years
        int[] count = new int[8];
        for(int i = 1; i < 8; i++)
            count[i] = 0;
        for(int i = 1900,firstDayOfTheYear=1; i < 1900+n; i++) {
          for(int month=1, monthDayOne = firstDayOfTheYear; month <= 12; month++) {
            if(monthDayOne > 0 && monthDayOne <= 2)
              count[8-monthDayOne]++;
            else
              count[monthDayOne-2]++;
            if(month==2){
              if(isLeapYear(i))
                monthDayOne++;
            }
            else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
              monthDayOne += 3;
            else
              monthDayOne += 2;
            monthDayOne = monthDayOne > 7 ? monthDayOne%7: monthDayOne; //recalibrate
          }
          firstDayOfTheYear++;
          firstDayOfTheYear = firstDayOfTheYear > 7? firstDayOfTheYear % 7 : firstDayOfTheYear;
        }
        //In the order specified
        out.print(count[6]+" ");
        out.print(count[7]+" ");
        out.print(count[1]+" ");
        out.print(count[2]+" ");
        out.print(count[3]+" ");
        out.print(count[4]+" ");
        out.print(count[5]+" \n");
        out.close();
        System.exit(0);
      }
    }

使用switch case语句,它将使您的逻辑更容易理解

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM