Daily Programmer Challenge #397 (here)
Roman Numeral Comparison
Compare two strings of faux roman numerals. The function should return true if the first string's numeral value is less than the second.
Note: These are not real roman numerals in the sense that their order does not impact their value. A simplification for convenience.
// Example: "II" "V" => true (2 < 5)
// "VV" "VI" => false (5+5 < 5+1)
// convert faux roman numeral to number
function calc(ronum){
var num = 0;
for(var xint = 0, len = ronum.length;xint < len;xint++){
if(ronum.charAt(xint) == 'M') num += 1000;
else if(ronum.charAt(xint) == 'D') num += 500;
else if(ronum.charAt(xint) == 'C') num += 100;
else if(ronum.charAt(xint) == 'L') num += 50;
else if(ronum.charAt(xint) == 'X') num += 10;
else if(ronum.charAt(xint) == 'V') num += 5;
else if(ronum.charAt(xint) == 'I') num += 1;
}
return num;
}
// payload comparison. one < two = true, one >= two = false
function compare(ronum_one, ronum_two){
var num_one = calc(ronum_one);
var num_two = calc(ronum_two);
return num_one < num_two;
}
// The values are not roman numeral format, but represent a number,
// so they will be randomly generated outside conventional order.
var ronums = ['M', 'D', 'C', 'L', 'X', 'V', 'I'];
function makeRonum(){
var str = "";
var len = Math.round(Math.random()*10) + 1;
for(var xint = 0;xint < len;xint++)
str += ronums[(Math.round(Math.random()*(ronums.length-1)))];
return str;
}
function test(){
var one = makeRonum();
var two = makeRonum();
if(compare(one, two)){
console.log("true, " + calc(one) + " < " + calc(two) + " | " + one + " < " + two);
}else{
console.log("false, " + calc(one) + " >= " + calc(two) + " | " + one + " >= " + two);
}
}
test();
test();
test();
test();
No comments:
Post a Comment