Skip to content

Instantly share code, notes, and snippets.

@mqrelly
Created July 23, 2014 21:15
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 mqrelly/16f162289a4970b8fe06 to your computer and use it in GitHub Desktop.
Save mqrelly/16f162289a4970b8fe06 to your computer and use it in GitHub Desktop.
Budapest ClojureDojo (2014.07.22) - Get the Roman numeral representation of a number
(def roman-digits ["I" "V" "X" "L" "C" "D" "M"])
(defn get-digit-set [exponent]
(let [base-index (* 2 exponent)]
[
[""
(roman-digits base-index)
(roman-digits (+ base-index 1))]
[
(roman-digits (+ base-index 1))
(roman-digits base-index)
(roman-digits (+ base-index 2))]
]))
(def digit-patterns { 0 '()
1 '(0 1)
2 '(0 1 1)
3 '(0 1 1 1)
4 '(1 2)
5 '(2)})
(defn single-to-roman [n digit-set]
(let [i (if (<= n 5) n (- n 5))
m (digit-set (if (<= n 5) 0 1))
s (digit-patterns i)]
(apply str (map m s))
)
)
(defn to-roman [n]
(loop [n n
exp 0
acc-roman-str ""]
(let [digit-set (get-digit-set exp)
single-digit (unchecked-remainder-int n 10)
next-roman-str (str (single-to-roman single-digit digit-set) acc-roman-str)]
(if (= exp 2)
next-roman-str
(recur (unchecked-divide-int n 10)
(inc exp)
next-roman-str)))))
(to-roman 637)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment