Friday, 14 March 2014

Romanize integers and deromanize strings



First example
function roman_to_arabic(text){
  var result =0 ;;
  var size = text.length- 1;
  for (var i=0 ;i <=size;i++){
    if(text[i] == "M"){
       result +=1000;
    } else if(text[ i] =="D" && text[i+ 1] =="D" ){
       result +=500;
    }
    else if(text [i] == "D"){
       result +=500 ;
    }
    else if(text [i] == "C"){
       if(text[i+ 1] =="M" || text[i+1] == "D" ){
        result -=100;
       }      
       else{
        result +=100;
       }
    }
    else if(text [i] == "L"){
       result +=50 ;
    }
    else if(text [i] == "X"){
       if(text[i+ 1] =="C" || text[ i+1] == "L" ){
        result -=10;
       }      
       else{
        result +=10;
       }
    }
    else if(text [i] == "V"){
       result +=5 ;
    }
    else if(text [i] == "I"){
       if(text[i+1] =="X" || text[ i+1] == "V" ){
        result -=1;
       }      
       else{
        result +=1;
       }
    }
  }
  return result ;
}

More complex example
function romanize (num) {
    if (!+num )
        return false;
    var digits = String(+num ).split("" ),
        key = ["" ,"C","CC" ,"CCC","CD" ,"D","DC" ,"DCC","DCCC" ,"CM",
               "","X" ,"XX","XXX" ,"XL","L" ,"LX","LXX" ,"LXXX","XC" ,
               "","I" ,"II","III" ,"IV","V" ,"VI","VII" ,"VIII","IX" ],
        roman = "",
        i = 3;
    while (i --)
        roman = (key[+ digits.pop () + ( i * 10)] || "") + roman;
    return Array(+digits.join("" ) + 1).join( "M") + roman;
}

function deromanize (str) {
    var str = str.toUpperCase (),
        validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/ ,
        token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        key = {M:1000 ,CM :900 ,D :500 ,CD :400 ,C :100 ,XC :90 ,L :50 ,XL :40 ,X :10 ,IX :9 ,V :5 ,IV :4 ,I :1 },
        num = 0, m;
    if (!(str && validator.test(str)))
        return false;
    while (m = token.exec( str))
        num += key[m[0]];
    return num;
}


No comments:

Post a Comment