Permalink
Browse files

New kata: Roman Numerals

  • Loading branch information...
1 parent fb73a7a commit bef12528cb3e56cff2578bee85b221e79ed8fcc0 @gam committed May 3, 2012
View
@@ -0,0 +1,10 @@
+/target
+/lib
+/classes
+/checkouts
+pom.xml
+*.jar
+*.class
+.lein-deps-sum
+.lein-failures
+.lein-plugins
View
@@ -0,0 +1,13 @@
+# roman-numerals
+
+A Clojure kata.
+
+## Usage
+
+To start the autorunner for clojure.test and Midje:
+
+ $ lein midje --lazytest
+
+## License
+
+Copyright
@@ -0,0 +1,8 @@
+(defproject roman-numerals "1.0.0-SNAPSHOT"
+ :description "Clojure implementation of the 'roman-numerals' kata."
+ :url "http://github.com/gam/clojure-katas/roman-numerals"
+ :license {:name "Eclipse Public License - v 1.0"
+ :url "http://www.eclipse.org/legal/epl-v10.html"}
+ :dependencies [[org.clojure/clojure "1.4.0"]]
+ :profiles {:dev {:dependencies [[midje "1.4.0-beta1"]]}}
+ :min-lein-version "2.0.0")
@@ -0,0 +1,23 @@
+(ns roman-numerals.kata)
+
+(def ^:dynamic *translations*
+ [[100 ["C" "D" "M"]]
+ [10 ["X" "L" "C"]]
+ [1 ["I" "V" "X"]]])
+
+(defn translate [num [base [one five ten]]]
+ (loop [acc [] rem num]
+ (if (< rem base) [acc rem]
+ (let [base-times (partial * base)
+ add (partial conj acc)]
+ (cond
+ (= rem (base-times 9)) (recur (add one ten) (- rem (base-times 9)))
+ (>= rem (base-times 5)) (recur (add five) (- rem (base-times 5)))
+ (= rem (base-times 4)) (recur (add one five) (- rem (base-times 4)))
+ (>= rem base) (recur (add one) (- rem base)))))))
+
+(defn to-roman [number]
+ (loop [acc [] rem number translations *translations*]
+ (if (empty? translations) (apply str (flatten acc))
+ (let [[acc1 rem1] (translate rem (first translations))]
+ (recur (conj acc acc1) rem1 (rest translations))))))
@@ -0,0 +1,48 @@
+(ns roman-numerals.kata-test
+ (:use roman-numerals.kata
+ [clojure.test :only (deftest testing is are with-test)]))
+
+(deftest arabic-to-roman-numbers
+ (are [arabic roman] (= roman (to-roman arabic))
+ 1 "I"
+ 2 "II"
+ 3 "III"
+ 4 "IV"
+ 5 "V"
+ 6 "VI"
+ 7 "VII"
+ 8 "VIII"
+ 9 "IX"
+ 10 "X"
+ 11 "XI"
+ 12 "XII"
+ 13 "XIII"
+ 14 "XIV"
+ 15 "XV"
+ 16 "XVI"
+ 17 "XVII"
+ 18 "XVIII"
+ 19 "XIX"
+ 20 "XX"
+ 21 "XXI"
+ 22 "XXII"
+ 23 "XXIII"
+ 24 "XXIV"
+ 25 "XXV"
+ 26 "XXVI"
+ 27 "XXVII"
+ 28 "XXVIII"
+ 29 "XXIX"
+ 30 "XXX"
+ 31 "XXXI"
+ 32 "XXXII"
+ 33 "XXXIII"
+ 34 "XXXIV"
+ 35 "XXXV"
+ 36 "XXXVI"
+ 37 "XXXVII"
+ 38 "XXXVIII"
+ 39 "XXXIX"
+ 40 "XL"))
+
+

0 comments on commit bef1252

Please sign in to comment.