Skip to content

Instantly share code, notes, and snippets.

@gsrai
Created November 14, 2020 19:57
Show Gist options
  • Save gsrai/70ac0aa12777b31dc3cd7ff6fe807c9f to your computer and use it in GitHub Desktop.
Save gsrai/70ac0aa12777b31dc3cd7ff6fe807c9f to your computer and use it in GitHub Desktop.
Roman numeral kata in Clojure
(ns roman-numeral-converter.core
(:require [clojure.test :refer [deftest is run-tests]]
[clojure.string :refer [replace]]))
(def numeral-mapping {1 "I" 5 "V" 10 "X" 50 "L" 100 "C" 500 "D" 1000 "M"})
(defn arabic-to-roman [n]
(loop [[x & xs :as all] (-> numeral-mapping keys sort reverse)
romanised ""
num n]
(if x
(if (>= num x)
(recur all (str romanised (get numeral-mapping x)) (- num x))
(recur xs romanised num))
(-> romanised
(replace "IIII" "IV")
(replace "VIV" "IX")
(replace "XXXX" "XL")
(replace "LXL" "XC")
(replace "CCCC" "CD")
(replace "DCD" "CM")))))
(deftest test-one
(is (= (arabic-to-roman 1) "I")))
(deftest test-five
(is (= (arabic-to-roman 5) "V")))
(deftest test-ten
(is (= (arabic-to-roman 10) "X")))
(deftest test-fifty
(is (= (arabic-to-roman 50) "L")))
(deftest test-one-hundred
(is (= (arabic-to-roman 100) "C")))
(deftest test-five-hundred
(is (= (arabic-to-roman 500) "D")))
(deftest test-one-thousand
(is (= (arabic-to-roman 1000) "M")))
(deftest test-888
(is (= (arabic-to-roman 888) "DCCCLXXXVIII")))
(deftest test-889
(is (= (arabic-to-roman 889) "DCCCLXXXIX")))
(deftest test-zero
(is (= (arabic-to-roman 0) "")))
(deftest test-four
(is (= (arabic-to-roman 4) "IV")))
(deftest test-decending-order-tally
(is (= (arabic-to-roman 16) "XVI")))
(deftest test-upper-limits
(is (= (arabic-to-roman 3999) "MMMCMXCIX")))
(run-tests 'roman-numeral-converter.core)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment