Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
(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

(require '[clojure.test :refer :all])

(def roman-lookup {\I 1 \V 5 \X 10 \L 50 \C 100 \D 500 \M 1000})

(defn decimalise [tuple] (map (fn [char] (roman-lookup char 0)) tuple))

(defn tupelise [a-seq] (partition 2 2 (repeat nil) (reverse a-seq)))

(defn eval-roman-tuple 
  [tuple]
  (let [[f-val s-val :as dec-tuple] (decimalise tuple)]
    (if (> f-val s-val)
        (- f-val s-val)
      (reduce + dec-tuple))))

(defn roman->decimal [roman-numeral] 
  (reduce + (map eval-roman-tuple (tupelise roman-numeral))))

(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)
Owner

biomunky 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