Created
December 7, 2012 13:29
-
-
Save ponkore/4233289 to your computer and use it in GitHub Desktop.
Project Euler Problem 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Project Euler Problem 1 | |
;;; http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%201 | |
;;; | |
;;; 10未満の自然数のうち、3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり、 これらの合計は 23 になる。 | |
;;; 同じようにして、1,000 未満の 3 か 5 の倍数になっている数字の合計を求めよ。 | |
;;; 3 もしくは 5の倍数の場合 true、そうでない場合 false を返す filter 判定用関数 | |
(defn fizz-or-buzz? | |
"3か5で割り切れるならtrue、そうでないならfalseを返す。" | |
[n] | |
(or (zero? (mod n 3)) (zero? (mod n 5)))) | |
(defn problem-1 | |
"Projec Euler Problem#1" | |
([] (problem-1 1000)) | |
([n] (->> (range 1 n) (filter fizz-or-buzz?) (reduce +)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Project Euler Problem 1 | |
;;; http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%201 | |
;;; | |
;;; 10未満の自然数のうち、3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり、 これらの合計は 23 になる。 | |
;;; 同じようにして、1,000 未満の 3 か 5 の倍数になっている数字の合計を求めよ。 | |
;;; iterate で繰り返すことができるよう、一つの引数を取り次へとつながるパラメータを戻り値として返す、 | |
;;; シーケンスジェネレータっぽいやつを作る。 | |
(defn fizzbuzz-seq | |
[[result n]] | |
(let [incn (inc n)] | |
[(or (zero? (mod incn 3)) (zero? (mod incn 5))) (inc n)])) | |
;;; テスト | |
;(take 10 (iterate fizzbuzz-seq [false 1])) | |
;=> ([false 1] [false 2] [true 3] [false 4] [true 5] [true 6] [false 7] [false 8] [true 9] [true 10]) | |
;;; それをフィルタする。良い感じ。 | |
;(->> (take 10 (iterate fizzbuzz-seq [false 1])) (filter first)) | |
;=> ([true 3] [true 5] [true 6] [true 9] [true 10]) | |
;;; 答え | |
(defn problem-1-2 | |
([] (problem-1-2 1000)) | |
([n] (->> (iterate fizzbuzz-seq [false 1]) | |
(take n) | |
(filter first) | |
(map second) | |
(reduce +)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ちなみに私は
(apply + coll)
派ですが,この場合はapply
で書いてもreduce
で書いてもどちらでもいいと思います.その理由は,...と書きはじめたら長くなったので別記事にまとめてみました.ご参考まで. > http://tnoda-clojure.tumblr.com/post/37700304493/apply-and-reduce