我的USACO星期五第十三解决方案出了什么问题?

时间:2016-10-08 02:21:26

标签: java

来自USACO培训页面,星期五,十三 问题是要计算第13次将在1990年1月1日到1990年12月31日+ N-1的每周的每一天降落的频率,其中给出N. 1990年1月1日是星期一,考虑到闰年。该计划应该打印星期六的13号,然后是周日的星期三,等等。  我似乎无法在我的代码中找到问题,而且我已经尝试了几天了。编辑 - 您不能使用该程序的日期函数 我对N = 20的输出是37 34 35 34 36 36 35

它应该是36 33 34 33 35 35 34

import java.io.*;
class friday {

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader("friday.in"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("friday.out")));

    int N = Integer.parseInt(in.readLine());
    int[] monthDays = {0,31,28,31,30,31,30,31,31,30,31,30,31};

    int firstdayNo=2;
    int THIRdayNo;
    int[] counter = new int[8];
    Arrays.fill(counter, 1); 
    for (int j=1900; j<1900+N;j++) {
        if (j%4==0 && j%100 !=0 || j%400==0) { 
            monthDays[2]=29;
        }

        else {
            monthDays[2]=28;
        }



        for (int i=1; i<13; i++) {
            if (firstdayNo==2) {
                THIRdayNo=7;

            }
            else {
                THIRdayNo=(firstdayNo+12)%7; 
            }
            counter[THIRdayNo]++;
            firstdayNo= (monthDays[i]%7) +firstdayNo; 

            if (firstdayNo>7) {firstdayNo=firstdayNo-7;}
            // to here, and you are done
            }

    }
    out.println(+counter[7]+" "+ counter[1]+" "+counter[2]+" "+ counter[3]+ " "+counter[4]+" "+counter[5]+" "+counter[6]);
    in.close();
    out.close();
    System.exit(0);
}   

}

1 个答案:

答案 0 :(得分:0)

java.util.Calendar作为标准民事日期的

GregorianCalendar已经处理了从一个月到一个月(仅使用Calendar.add(Calendar.MONTH, 1)),也跟踪闰年并知道如何处理DAY_OF_WEEK。所以:

  static public void main(String[] arg) {
    int N=20;

    TreeMap<Integer, Integer> dayOfWeekOccurs=new TreeMap<>();
    // DAY_OF_WEEK is 1-based
    for(int dayOfWeek=1; dayOfWeek<=7; dayOfWeek++) {
      dayOfWeekOccurs.put(dayOfWeek, 0);
    }

    // month is 0-based, DAY_OF_MONTH is 1-based, YEAR is 0-based.
    // Consistency be damn'd.
    GregorianCalendar start=new GregorianCalendar(1990, 0, 13);
    GregorianCalendar end=new GregorianCalendar(1990+N-1, 11, 31);

    while(start.compareTo(end)<0) {
      start.add(Calendar.MONTH, 1);
      int dayOfWeek=start.get(Calendar.DAY_OF_WEEK);
      int oldOccurs=dayOfWeekOccurs.get(dayOfWeek);
      dayOfWeekOccurs.put(dayOfWeek, ++oldOccurs);
    }

    System.out.println("13 on Sun: "+dayOfWeekOccurs.get(Calendar.SUNDAY)); 
    System.out.println("13 on Mon: "+dayOfWeekOccurs.get(Calendar.MONDAY)); 
    System.out.println("13 on Tue: "+dayOfWeekOccurs.get(Calendar.TUESDAY)); 
    System.out.println("13 on Wed: "+dayOfWeekOccurs.get(Calendar.WEDNESDAY)); 
    System.out.println("13 on Thu: "+dayOfWeekOccurs.get(Calendar.THURSDAY)); 
    System.out.println("13 on Fri: "+dayOfWeekOccurs.get(Calendar.FRIDAY)); 
    System.out.println("13 on Sat: "+dayOfWeekOccurs.get(Calendar.SATURDAY)); 
  }