Skip to content

Instantly share code, notes, and snippets.

@attilapiros
Forked from erdos/num-to-roman.clj
Last active August 29, 2015 14:04
Show Gist options
  • Save attilapiros/bddec19b975e69d639cc to your computer and use it in GitHub Desktop.
Save attilapiros/bddec19b975e69d639cc to your computer and use it in GitHub Desktop.
(ns roman-nums.core
(:require
[clojure.test :refer [testing are]]))
(def ^:private roman-digits
[[1000 "M"] [900 "CM"]
[500 "D"] [400 "CD"]
[100 "C"] [90 "XC"]
[50 "L"] [40 "XL"]
[10 "X"] [9 "IX"]
[5 "V"] [4 "IV"]
[1 "I"]])
(defn num-to-roman
"Convert a number to roman"
[n]
(assert (integer? n))
(assert (not (neg? n)))
(loop [buf [], n n, d roman-digits]
(if (zero? n)
(apply str buf)
(let [[[value romnum] & tail] (drop-while #(< n (first %)) d) fac (quot n value)]
(recur (into buf (doall (repeat fac romnum))) (- n (* fac value)) tail)))))
(testing "some examples"
(are [i s] (= s (num-to-roman i))
1 "I", 2 "II",
3 "III", 4 "IV"
5 "V", 6 "VI", 7 "VII", 41 "XLI"
971 "CMLXXI", 871 "DCCCLXXI"
900 "CM", 91 "XCI"
9 "IX"
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment