第三日曜日の度数分布
第三日曜日になるday of monthの度数分布を求める。
import static java.time.DayOfWeek.SUNDAY; import java.time.YearMonth; import static java.time.temporal.TemporalAdjusters.dayOfWeekInMonth; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class ThirdSundayFD { public static void main(String[] args) { final YearMonth START = YearMonth.of(2016, 1); final YearMonth END = YearMonth.of(2017, 1); Map<Integer, Integer> fd = new HashMap<>(); for (YearMonth d = START; d.isBefore(END); d = d.plusMonths(1)) { fd.merge( d.atDay(1).with(dayOfWeekInMonth(3, SUNDAY)).getDayOfMonth(), 1, (o, n) -> ++o ); } new TreeMap<>(fd).forEach((k, v) -> System.out.println(k + " " + v)); } }
注意すべきはラムダ式(o, n) -> ++o
の前置インクリメント演算子。
これを後置にするとラムダ式の値はインクリメントする前の値になる。
実行すると、
$ java ThirdSundayFD 15 1 16 1 17 3 18 2 19 1 20 2 21 2
サンプル数を増やして、
final YearMonth START = YearMonth.of(1980, 1); final YearMonth END = YearMonth.of(2050, 1);
70年間840個分の度数分布表は、
15 121 16 118 17 121 18 119 19 120 20 121 21 120
度数が完全に等しいならそれぞれが840/7=120になるので、
まあ大体きちんと均されているようだ。