Last active
December 24, 2015 11:19
-
-
Save tonvanbart/6790573 to your computer and use it in GitHub Desktop.
Roman numerals kata in Clojure, discovering the algorithm by TDD.
IIRC the original description mentions the argument would not be greater than 3000 (as in a year A.D.), this is not checked. Arguments > 9999 will not be handled correctly.
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 tonvanbart.roman | |
(:use clojure.test) | |
(:require [clojure.string :as str])) | |
(defn convert-step | |
"one step converting a number to roman numerals" | |
[n unitsymbol fivesymbol tensymbol] | |
(cond | |
(< n 4) (apply str (repeat n unitsymbol)) | |
(< n 9) (str/join | |
(concat | |
(repeat (- 5 n) unitsymbol) | |
fivesymbol | |
(repeat (- n 5) unitsymbol))) | |
(= n 9) (str unitsymbol tensymbol))) | |
(defn convert | |
"convert a number to roman numerals" | |
([n] (convert n "")) | |
([n result] | |
(cond | |
(> n 1000) (let [part (convert-step (quot n 1000) "m" "" "")] | |
(recur (rem n 1000) part)) | |
(> n 100) (let [part (str result (convert-step (quot n 100) "c" "d" "m"))] | |
(recur (rem n 100) part)) | |
(> n 10) (let [part (str result (convert-step (quot n 10) "x" "l" "c"))] | |
(recur (rem n 10) part)) | |
:else (str result (convert-step n "i" "v" "x"))))) | |
; tests | |
(deftest conversions | |
(are [number converted] (= converted (convert number)) | |
1 "i" | |
2 "ii" | |
3 "iii" | |
4 "iv" | |
8 "viii" | |
9 "ix" | |
12 "xii" | |
19 "xix" | |
39 "xxxix" | |
49 "xlix" | |
208 "ccviii" | |
1958 "mcmlviii" | |
2008 "mmviii" | |
2112 "mmcxii")) | |
(run-tests) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment