Created
April 15, 2013 14:39
-
-
Save jacegu/5388586 to your computer and use it in GitHub Desktop.
Roman numeral kata in erlang. Wondering if there is a better/more idiomatic way to approach the problem.
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(kata). | |
-include_lib("eunit/include/eunit.hrl"). | |
to_roman(Arabic) when Arabic >= 50 -> string:concat("L", to_roman(Arabic - 50)); | |
to_roman(Arabic) when Arabic >= 10 -> string:concat("X", to_roman(Arabic - 10)); | |
to_roman(Arabic) when Arabic >= 5 -> string:concat("V", to_roman(Arabic - 5)); | |
to_roman(Arabic) when Arabic =:= 4 -> string:concat("IV", to_roman(Arabic - 4)); | |
to_roman(Arabic) when Arabic >= 1 -> string:concat("I", to_roman(Arabic - 1)); | |
to_roman(_) -> "". | |
it_transform_the_number_1_to_roman_numeral_I_test() -> | |
?assertEqual("I", to_roman(1)). | |
it_transform_the_number_2_to_roman_numeral_II_test() -> | |
?assertEqual("II", to_roman(2)). | |
it_transform_the_number_3_to_roman_numeral_III_test() -> | |
?assertEqual("III", to_roman(3)). | |
it_transform_the_number_4_to_roman_numeral_IV_test() -> | |
?assertEqual("IV", to_roman(4)). | |
it_transform_the_number_5_to_roman_numeral_V_test() -> | |
?assertEqual("V", to_roman(5)). | |
it_transform_the_number_7_to_roman_numeral_VII_test() -> | |
?assertEqual("VII", to_roman(7)). | |
it_transforms_the_number_10_to_roman_numeral_X_test() -> | |
?assertEqual("X", to_roman(10)). | |
it_transforms_the_number_37_to_roman_numeral_XXXVII_test() -> | |
?assertEqual("XXXVII", to_roman(37)). | |
it_transforms_the_number_57_to_roman_numeral_LVII_test() -> | |
?assertEqual("LVII", to_roman(57)). |
Made a little improvement to the code:
to_roman(0) -> "";
to_roman(Arabic) ->
{Equivalence, Value} = closest_equivalence_to(Arabic),
Equivalence ++ to_roman(Arabic - Value).
closest_equivalence_to(Number) when Number >= 10 -> {"X", 10};
closest_equivalence_to(Number) when Number == 9 -> {"IX", 9};
closest_equivalence_to(Number) when Number >= 5 -> {"V", 5};
closest_equivalence_to(Number) when Number == 4 -> {"IV", 4};
closest_equivalence_to(Number) when Number >= 1 -> {"I", 1}.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are missing cases (9, 40s etc...) but it's just to get the idea...