Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created January 4, 2013 09:04
Show Gist options
  • Save bouzuya/4451081 to your computer and use it in GitHub Desktop.
Save bouzuya/4451081 to your computer and use it in GitHub Desktop.
;;; 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)))
@ypsilon-takai
Copy link

変数が多いのをすこし気にしています。 @tnoda のコードはいつも -> などがうまく使われていてすっきりしている気がします。

-> などを使うと意図が見えにくくなるという欠点もありますよね。複数回使うからでなくて、説明のために変数に束縛するというのもありだと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment