Skip to content

Instantly share code, notes, and snippets.

@dzenzes
Last active June 29, 2016 17:07
Show Gist options
  • Save dzenzes/c3b6122685fe26deae3cb786fd0aaa60 to your computer and use it in GitHub Desktop.
Save dzenzes/c3b6122685fe26deae3cb786fd0aaa60 to your computer and use it in GitHub Desktop.
(ns roman-numeral)
(def number-to-roman-numeral
[
{:number 1000 :roman "M"}
{:number 900 :roman "CM"}
{:number 500 :roman "D"}
{:number 400 :roman "CD"}
{:number 100 :roman "C"}
{:number 90 :roman "XC"}
{:number 50 :roman "L"}
{:number 40 :roman "XL"}
{:number 10 :roman "X"}
{:number 9 :roman "IX"}
{:number 5 :roman "V"}
{:number 4 :roman "IV"}
{:number 1 :roman "I"}])
(defn to-roman-numeral
"converts a number into its roman numeral representation"
[number]
(loop [currentNumber number [currentMapping & restOfMapping] number-to-roman-numeral result ""]
(if (= currentMapping nil)
result
(if (>= currentNumber (:number currentMapping))
(recur (- currentNumber (:number currentMapping)) (cons currentMapping restOfMapping) (str result (:roman currentMapping)))
(recur currentNumber restOfMapping result)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment