Euler : Problem 19

Posted by TAKAIY On 2011年5月4日水曜日 0 コメント

公式とかつかってもよさそうだったけど、順にやってみることにした。
1年の最初の曜日を与えると、各月の1日の曜日を返す処理を作って、1900年1月1日から順に1日が何曜日か計算してます。

もっと汎用的な処理を作るべきかなぁ。


;;
;; Problem 19 : 2011/4/27
;; "Elapsed time: 0.492521 msecs" 1900-1900
;; "Elapsed time: 1.898565 msecs" 1900-2000

(def month-non-leap [31 28 31 30 31 30 31 31 30 31 30 31])
(def month-leap [31 29 31 30 31 30 31 31 30 31 30 31])

(defn leap-year? [year]
(cond (not (zero? (rem year 4))) false
(zero? (rem year 400)) true
(zero? (rem year 100)) false
:else true))

(defn get-month [is-leap]
(if is-leap
month-leap
month-non-leap))

(defn first-days [is-leap first-day]
(loop [month-list (get-month is-leap)
res-list (list first-day)]
(if (empty? month-list)
res-list
(let [month-day (first month-list)]
(recur (rest month-list)
(cons (rem (+ (first res-list) month-day) 7) res-list))))))

(defn count-sunday [start-year end-year first-day]
(loop [year-list (range start-year (inc end-year))
first-day first-day
sunday-count 0]
(if (empty? year-list)
sunday-count
(let [[next-first & data] (first-days (leap-year? (first year-list)) first-day)]
(recur (rest year-list)
next-first
(+ sunday-count (count (filter #(= % 0) data))))))))

(-
(count-sunday 1900 2000 1)
(count-sunday 1900 1900 1))


;;

0 コメント:

コメントを投稿