Last active
August 29, 2015 13:57
-
-
Save biomunky/9715453 to your computer and use it in GitHub Desktop.
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
(use 'clojure.test) | |
(use 'clojure.pprint) | |
(def roman-lookup {\I 1 \V 5 \X 10 \L 50 \C 100 \D 500 \M 1000}) | |
(defn roman-helper [curnt nxt agg] | |
(if (> nxt curnt) | |
(+ agg (- curnt)) | |
(+ agg curnt))) | |
(defn roman->decimal [aseq] | |
(loop [s aseq agg 0] | |
(let [f (roman-lookup (first s)) n (roman-lookup (second s)) r (rest s)] | |
(cond | |
(empty? s) agg | |
(nil? n) (+ agg f) | |
:else (recur r (roman-helper f n agg)))))) | |
(deftest roman-numerals | |
(is (== 1984 (roman->decimal "MCMLXXXIV"))) | |
(is (== 100 (roman->decimal "C"))) | |
(is (== 1 (roman->decimal "I"))) | |
(is (== 4 (roman->decimal "IV"))) | |
(is (== 1917 (roman->decimal "MCMXVII")))) | |
(run-tests) | |
;; and to roman ... cheat | |
(def decimal->roman (partial clojure.pprint/cl-format nil "~@R")) | |
(println (decimal->roman 1984)) |
lotia
commented
Mar 26, 2014
(use 'clojure.test)
(def roman-lookup {\I 1 \V 5 \X 10 \L 50 \C 100 \D 500 \M 1000})
(def a "MCMLXXXIV")
(defn roman-helper [[a b]]
(let [curnt (roman-lookup a 0) nxt (roman-lookup b 0)]
(if (> nxt curnt) (- curnt) curnt)))
(defn roman->decimal [roman]
(let [as-seq (conj (into [] roman) nil)
pairs (partition 2 1 as-seq)]
(apply + (map roman-helper pairs))))
(deftest roman-numerals
(is (== 1984 (roman->decimal "MCMLXXXIV")))
(is (== 100 (roman->decimal "C")))
(is (== 1 (roman->decimal "I")))
(is (== 4 (roman->decimal "IV")))
(is (== 1917 (roman->decimal "MCMXVII"))))
(run-tests)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment