Created
November 23, 2011 14:39
-
-
Save gigasquid/1388834 to your computer and use it in GitHub Desktop.
Roman Numbers (Clojure)
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
(ns roman-nums | |
(:use clojure.test)) | |
(def chart (zipmap [1 4 5 9 10 40 50 90 100 400 500 900 1000] | |
["I" "IV" "V" "IX" "X" "XL" "L" "XC" "C" "CD" "D" "CM" "M"])) | |
;; Using no tail recursion | |
(defn arabic-to-roman [n] | |
(let [[val c] (last | |
(filter #(>= n (first %)) | |
(sort-by first chart)))] | |
(if val | |
(str c (arabic-to-roman (- n val))) | |
""))) | |
(deftest basic-numbers | |
(is (= "I" (arabic-to-roman 1))) | |
(is (= "II" (arabic-to-roman 2))) | |
(is (= "III" (arabic-to-roman 3))) | |
(is (= "IV" (arabic-to-roman 4))) | |
(is (= "V" (arabic-to-roman 5))) | |
(is (= "VI" (arabic-to-roman 6))) | |
(is (= "VII" (arabic-to-roman 7))) | |
(is (= "VIII" (arabic-to-roman 8))) | |
(is (= "IX" (arabic-to-roman 9))) | |
(is (= "X" (arabic-to-roman 10)))) | |
(deftest more-advanced | |
(is (= "XX" (arabic-to-roman 20))) | |
(is (= "XL" (arabic-to-roman 40))) | |
(is (= "L" (arabic-to-roman 50))) | |
(is (= "XC" (arabic-to-roman 90))) | |
(is (= "C" (arabic-to-roman 100))) | |
(is (= "CD" (arabic-to-roman 400))) | |
(is (= "D" (arabic-to-roman 500))) | |
(is (= "CM" (arabic-to-roman 900))) | |
(is (= "M" (arabic-to-roman 1000)))) | |
(run-all-tests) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment