Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created June 6, 2014 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmchild/4527e3c926882461bd38 to your computer and use it in GitHub Desktop.
Save bmchild/4527e3c926882461bd38 to your computer and use it in GitHub Desktop.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var NumberMap = {};
NumberMap.I = 1;
NumberMap.V = 5;
NumberMap.X = 10;
NumberMap.L = 50;
NumberMap.C = 100;
NumberMap.D = 500;
NumberMap.M = 1000;
/*
* Main logic to get the decimal value
*/
function getDecimal(romanNumeral) {
var result = 0;
var numArray = convertToNumberArray(romanNumeral);
for(var x = 0; x < numArray.length;) {
// single value
if(numArray.length == (x + 1)) {
console.log('single number -> ' + numArray[x]);
result += numArray[x];
x++;
}
// need to subtract from 2nd value
else if(numArray[x] < numArray[x + 1]) {
console.log('subtract case. ' + numArray[x + 1] + ' - ' + numArray[x]);
result += numArray[x + 1] - numArray[x];
x += 2;
}
// large value
else {
console.log('large value ' + numArray[x]);
var repeatedTimes = countFirstRepeats(numArray, x);
result += (numArray[x] * repeatedTimes);
x += repeatedTimes;
}
console.log('x -> ' + x + ', length -> ' + numArray.length);
}
return result;
}
function countFirstRepeats (array, index) {
var number = array[index];
var i = index + 1;
var counter = 1;
for(counter; counter < 3; counter++) {
if(array[index + counter] != number) {
break;
}
}
console.log('# of repeats -> ' + i);
return counter;
}
function convertToNumberArray(romanNumeral) {
var array = [];
for( var i = 0; i < romanNumeral.length; i++ ) {
array.push( NumberMap[romanNumeral.charAt(i)] );
}
console.log(array);
return array;
}
$(function() {
$('form').submit(function(event){
event.preventDefault();
$('#results').html( getDecimal( $('#romanInput').val() ) );
}).submit();
});
</script>
</head>
<body>
<h1>Roman Numeral Calculator</h1>
<form>
Enter a Roman Numeral (I, V, X, L, C, D, M): <input type="text" pattern="[IVXLCDM]+" placeholder = "Roman Numerals Only" id="romanInput" value="MDCCLXXVI" /> <input type="submit" />
</form>
<h3>Results</h3>
<div id="results">
</div>
</body>
</html>
@bmchild
Copy link
Author

bmchild commented Jun 6, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment