Skip to content

Instantly share code, notes, and snippets.

@biomunky
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biomunky/9715453 to your computer and use it in GitHub Desktop.
Save biomunky/9715453 to your computer and use it in GitHub Desktop.
(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))
@biomunky
Copy link
Author

(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