Last active
December 17, 2015 03:08
-
-
Save gburd/5540916 to your computer and use it in GitHub Desktop.
Given any number output the roman numeral representation.
This file contains hidden or 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
| -module(roman_numerals). | |
| -compile(export_all). | |
| % dec_to_roman/1 : integer -> string | |
| % format the integer num using roman numerals | |
| decimal_to_roman(Num) -> | |
| decimal_to_roman(Num, "", | |
| [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], | |
| ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]). | |
| % dec_to_roman/4 : integer string [t number) (list string) -> string | |
| % append the numbers num formatted as roman numerals to the string s, | |
| % using the roman numerals in roman-numbers with corresponding | |
| % decimal values in decimal-values | |
| decimal_to_roman(0, Accum, _Decimals, _Romans) -> | |
| Accum; | |
| decimal_to_roman(Num, Accum, Decimals, Romans) -> | |
| F_el = hd(Decimals), | |
| if | |
| F_el =< Num -> | |
| decimal_to_roman(Num - F_el, Accum ++ hd(Romans), Decimals, Romans); | |
| F_el > Num -> | |
| decimal_to_roman(Num, Accum, tl(Decimals), tl(Romans)) | |
| end. | |
| % roman_to_decimal : string -> integer | |
| % convert a string with (uppercase) roman numerals to an integer | |
| roman_to_decimal("") -> 0; | |
| roman_to_decimal(Str) -> | |
| case length(Str) of | |
| 1 -> | |
| case list_to_atom(Str) of | |
| 'I' -> 1; | |
| 'V' -> 5; | |
| 'X' -> 10; | |
| 'L' -> 50; | |
| 'C' -> 100; | |
| 'D' -> 500; | |
| 'M' -> 1000; | |
| _ -> 0 | |
| end; | |
| _ -> | |
| roman_to_decimal(string:substr(Str, 3)) | |
| + case list_to_atom(string:substr(Str, 1, 2)) of | |
| 'IV' -> 4; | |
| 'IX' -> 9; | |
| 'XL' -> 40; | |
| 'XC' -> 90; | |
| 'CD' -> 400; | |
| 'CM' -> 900; | |
| _ -> | |
| roman_to_decimal(string:substr(Str, 1, 1)) | |
| + roman_to_decimal(string:substr(Str, 2, 1)) | |
| end | |
| end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment