Here's a Java implementation:
package time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Superstition calculates how frequently the 13th falls on each day of the week
* @author Michael
* @link https://stackoverflow.com/questions/31231343/on-what-days-does-the-thirteenth-occur-usaco
* @since 7/5/2015 10:31 AM
*/
public class Superstition {
public static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MMM-dd");
public static final int DEFAULT_MAX_YEARS = 400;
public static final String START_DATE = "1900-Jan-13";
public static final int MONTHS_PER_YEAR = 12;
public static void main(String[] args) {
Map<Integer, Integer> frequencies = new LinkedHashMap<Integer, Integer>() {{
put(Calendar.SUNDAY, 0);
put(Calendar.MONDAY, 0);
put(Calendar.TUESDAY, 0);
put(Calendar.WEDNESDAY, 0);
put(Calendar.THURSDAY, 0);
put(Calendar.FRIDAY, 0);
put(Calendar.SATURDAY, 0);
}};
try {
int maxYears = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_MAX_YEARS;
Calendar calendar = Calendar.getInstance();
calendar.setTime(DEFAULT_FORMAT.parse(START_DATE));
for (int i = 0; i < maxYears; ++i) {
for (int j = 0; j < MONTHS_PER_YEAR; ++j) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
frequencies.put(dayOfWeek, (frequencies.get(dayOfWeek) + 1));
calendar.add(Calendar.MONTH, 1);
}
}
} catch (ParseException e) {
e.printStackTrace();
} finally {
System.out.println(frequencies);
}
}
}
Here's the output for the years from 1900 to 2300:
com.intellij.rt.execution.application.AppMain time.Superstition
{1=687, 2=685, 3=685, 4=687, 5=684, 6=688, 7=684}
Process finished with exit code 0
As expected, the frequencies with which the 13th falls on each day of the week are roughly the same. Sum of values equals (# years)*(12 months per year), as it should be.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…