Skip to content

Instantly share code, notes, and snippets.

@rayshan
Last active January 4, 2016 19:49
Show Gist options
  • Save rayshan/8670186 to your computer and use it in GitHub Desktop.
Save rayshan/8670186 to your computer and use it in GitHub Desktop.
Number to / from roman numeral converter

Created by Matthew, Daniel, Corey and Ray during JS Study Group: Algorithms.

Converts numbers to and from roman numerals, up to 3999.

There are more mathmetical solutions to the problem but this works.

var input = [0, 1, 5, 1519, 3999]
var input2 = ["I", "VIII", "MMMCMXCIX", "IX", "V"]
definition = [
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"]
]
definition2 = {
M: 1000,
D: 500,
C: 100,
L: 50,
X: 10,
V: 5,
I: 1
}
toRoman = function (input) {
var _result = "";
if (input === 0) {
_result = "nulla"
} else {
for (var i = 0; i < definition.length; i++) {
while (input >= definition[i][0]) {
_result += definition[i][1];
input -= definition[i][0];
}
}
}
return _result;
}
toNum = function (input) {
var _result = 0
var _last = 0
for (var i = input.length - 1; i >= 0; i--) {
var num = definition2[input[i]]
_result += num * ((num < _last) ? -1 : 1); // Brackets V. important.
_last = num
}
return _result
}
// Main.
console.log("Roman Numerals to Numbers.");
for (var i = 0; i < input.length; i++) {
console.log(input2[i], "-->", toNum(input2[i]))
}
console.log("\n");
console.log("Numbers to Roman Numerals.");
for (var i = 0; i < input.length; i++) {
console.log(input[i], "-->", toRoman(input[i]))
}
Roman Numerals to Numbers.
I --> 1
VIII --> 8
MMMCMXCIX --> 3999
IX --> 9
V --> 5


Numbers to Roman Numerals.
0 '-->' 'nulla'
1 '-->' 'I'
5 '-->' 'V'
1519 '-->' 'MDXIX'
3999 '-->' 'MMMCMXCIX'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment