Roman Numerals
by webproger on 2020-03-17
/* Regular Expression
M{1,3}
((C{1,3})([^DM]|$))|(CD)|(DC{0,3})|(CM)
((X{1,3})([^LC]|$))|(XL)|(LX{0,3})|(XC)
((I{1,3})([^VX]|$))|(IV)|(VI{0,3})|(IX)
*/

// Javascript
function 2arabic(c) {
    switch(c) {
        case 'I': return    1; break;
        case 'V': return    5; break;
        case 'X': return   10; break;
        case 'L': return   50; break;
        case 'C': return  100; break;
        case 'D': return  500; break;
        case 'M': return 1000; break;
    }
}

var roman = 'MCMLXVIII';
var arabic = 0;
var previous = 0;
var current = 0;
for(i=0; i<roman.length; i++) {
    current
        = 2arabic(roman.charAt(i));
    if(previous && previous<current)
        arabic -= previous;
    else arabic += previous;
    previous = current;
}
arabic += current;