Created
July 23, 2014 21:15
-
-
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
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
(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