Created
January 4, 2013 09:04
-
-
Save bouzuya/4451081 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 #22 | |
;;; http://projecteuler.net/problem=22 | |
;;; http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2022 | |
; [org.clojure/data.csv "0.1.2"] | |
(require '[clojure.test :refer [deftest is]] | |
'[clojure.data.csv :as csv]) | |
(defn char-score | |
[c] | |
(- (Character/getNumericValue c) 9)) | |
(defn str-score | |
[s] | |
(apply + (map char-score s))) | |
(defn problem-22 | |
([] (problem-22 "names.txt")) | |
([file] | |
(let [names (first (csv/read-csv (slurp file))) | |
sorted (sort names) | |
scores (map str-score sorted)] | |
(apply + | |
(map-indexed | |
(fn [idx score] | |
(* (inc idx) score)) scores))))) | |
(deftest char-score-test | |
(is (= (char-score \C) 3)) | |
(is (= (char-score \O) 15)) | |
(is (= (char-score \L) 12)) | |
(is (= (char-score \I) 9)) | |
(is (= (char-score \N) 14))) | |
(deftest str-score-test | |
(is (= (str-score "COLIN") 53)) | |
(is (= (str-score "YUKIHO") 89))) | |
(deftest problem-22-test | |
(is (= (problem-22) 871198282))) |
変数が多いのをすこし気にしています。 @tnoda のコードはいつも -> などがうまく使われていてすっきりしている気がします。
->
などを使うと意図が見えにくくなるという欠点もありますよね。複数回使うからでなくて、説明のために変数に束縛するというのもありだと思います。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
edn ですね.JSON よりも速いので,Clojure で使うだけなら迷うことはないですね.参考→ http://tnoda-clojure.tumblr.com/post/28499910150/collection-literals-instead-of-json (edn が発表される前に書いたもの)