Last active
January 4, 2016 01:59
-
-
Save gdeer81/8551776 to your computer and use it in GitHub Desktop.
roman numeral kata in 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
;; in this kata we want to be able to convert a string to its roman numeral value | |
;;Roman numerals are written in descending order so we should be able to parse | |
;;the string and add up the values | |
;;the only issue is the subtraction rule | |
;; iv = 4 | |
;; we'll have to split the string into a vector of characters | |
;; convert each of those characters into a value | |
;; reduce the all those values into one final value | |
(def roman-nums {\I 1 | |
\V 5 | |
\X 10 | |
\L 50 | |
\C 100 | |
\D 500 | |
\M 1000}) | |
(defn roman-rules [[b a]] (if (< a b) (- a) a)) | |
(defn roman-numeral-value [s] | |
(reduce + (map roman-rules (partition 2 1 (cons 0 (map roman-nums (reverse s))))))) | |
;;tests for roman-rules | |
(and | |
(= -1 (roman-rules [5 1])) | |
(= 1 (roman-rules [1 1]))) | |
;;simple cases | |
(and | |
(= 1 (roman-numeral-value "I")) | |
(= 2 (roman-numeral-value "II")) | |
(= 10 (roman-numeral-value "X")) | |
(= 20 (roman-numeral-value "XX")) | |
(= 1001 (roman-numeral-value "MI"))) | |
;;tests for strings with subtraction rules | |
(and | |
(= 4 (roman-numeral-value "IV")) | |
(= 14 (roman-numeral-value "XIV")) | |
(= 40 (roman-numeral-value "XL"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment