Skip to content

Instantly share code, notes, and snippets.

@erdos
Forked from gfrivolt/num-to-roman.clj
Last active August 29, 2015 14:04
Show Gist options
  • Save erdos/3a403dd8768f4b48fc1f to your computer and use it in GitHub Desktop.
Save erdos/3a403dd8768f4b48fc1f 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]
(if (zero? n)
(apply str buf)
(let [[value romnum] (some #(if (>= n (first %)) %) roman-digits)]
(recur (conj buf romnum) (- n value))))))
(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"))
@attilapiros
Copy link

I might be wrong especially at this early hour but at my place the unit tests are failing

  • either the result string should be reversed, like at line 21: (apply str (reverse buf))
  • or better to use an array as a buf:
    at line 19: (loop [buf [], n n]
    and use the generic conj instead of cons:
    at line 23: (conj buf romnum)

@erdos
Copy link
Author

erdos commented Jul 31, 2014

Thank you for your feedback, i fixed the code according to the second option. I am still not sure however why the tests do not fail on my machine. Thanks again, e.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment