Last active
February 29, 2020 21:15
-
-
Save calizarr/ad18268bc888de597570665d28053d23 to your computer and use it in GitHub Desktop.
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
(setq numerals | |
'((ones "" "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX") | |
(tens "" "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC") | |
(hundreds "" "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM") | |
(thousands "" "M" "MM" "MMM"))) | |
(defun divmod (x y) | |
"Helper function to divide X by Y and return the quotient and remainder." | |
(let | |
((quotient (/ x y)) | |
(remainder (% x y))) | |
(cl-values quotient remainder))) | |
(defun to-roman-iterative (number) | |
"Iterative version of the to-roman function. Takes an arabic NUMBER to convert to roman numberal." | |
(let ((roman ())) | |
(-map (lambda (place) | |
(let* | |
((finalize (divmod number 10)) | |
(quotient (elt finalize 0)) | |
(remainder (elt finalize 1))) | |
(setq roman (cons (elt (cdr (assoc (elt place 0) numerals)) remainder) roman)) | |
(setq number quotient) | |
roman)) | |
numerals) | |
(mapconcat 'identity roman ""))) | |
(defun helper (numerals roman number) | |
"Helper function for to-roman. Takes a NUMERALS alist, ROMAN nil, NUMBER to convert to Roman." | |
(if (not numerals) | |
roman | |
(let* | |
((finalize (divmod number 10)) | |
(quotient (elt finalize 0)) | |
(remainder (elt finalize 1)) | |
(place (car (car numerals))) | |
(new-roman (cons (elt (cdr (assoc place numerals)) remainder) roman))) | |
(helper (cdr numerals) new-roman quotient)))) | |
(defun to-roman (number) | |
"Takes an arabic NUMBER to convert to roman numeral." | |
(mapconcat 'identity (helper numerals () number) "")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment