Tell us what’s happening:
Hi! So the problem with code currently is its reading 4 (IV or IIII) as 9 values (IX or VIIII). I know where the problem is in the code (look for comment) but I’m not sure how to solve it without creating more issues with 4s and 9s .
The way the algorithm works is if num=43, the largest number that can be subtracted that is equivalent to a roman numeral is 10 ( X) each time a numeral is added to the variable “roman”, that roman numerals equivalent is subtracted from num. This is repeated.
43-10=33… roman: X
33-10=23… roman: XX
23-10=13… roman: XXX
13-10=3… roman:XXXX
Since 4 roman numerals are found in a row, then its converted to XL
3-1=2… roman: XLI
2-1=1… roman: XLII
1-1=0. …roman: XLIII
While loop ends.
This becomes a problem for 44 because at XLIIII the algorithm interprets this as XIX (because of the 9’s regex pattern) instead of XLIV.
Your code so far
function convertToRoman(num) {
let numArr=[1,5,10,50,100,500,1000];
let romanArr=['I','V','X','L','C','D','M'];
let roman="";
//for loop going backwards through numArrr.
for (let i=numArr.length-1;i>=0;i--){
//while num is larger than 1. If 0, then that means num value has been converted to roman variable
while (num>=numArr[i]){
roman=roman.concat(romanArr[i]);
num-=numArr[i]; //substracting value of roman numerial from number. goes backwards through numArr array to subtract largest number possible.
let regexA=RegExp(romanArr[i]+'{4}'); //locating pattern that signifies a 4 such as IIII
let regexB=RegExp('\\w'+romanArr[i]+'{4}');
console.log('after while: ' + roman); //locating pattern that signifies a 9 such as VIIII
//replacing 9 patterns first since 4 patterns are inherently in 9 patterns. THIS BECOMES A PROBLEM FOR INPUTS LISTED BELOW: 44, 649, etc.
if (regexB.test(roman)) {
roman=roman.replace(regexB, romanArr[i]+romanArr[i+2]);
}
//replacing 4 patterns
else if(regexA.test(roman)){
roman=roman.replace(regexA, romanArr[i]+romanArr[i+1]);
}
}
}
console.log('final: '+roman);
return roman;
}
convertToRoman(44);
convertToRoman(649);
convertToRoman(1004);
convertToRoman(2014);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
.
Challenge: Roman Numeral Converter
Link to the challenge: