Hi !
I just finished the certification project Roman-Numeral Converter on the Javascript section, but I’m still a bit lost at how the script behaves, and this was by far the hardest project for me.
so after reading the hints, i ended up with this.
I don’t usually post in any type of forum, but i thought this would be a good place to
get corrections and feedback, while helping those i can. Is there something specially wrong with the way this was done? Is there a way to use a smaller array to compare?
Thanks!
It’s passing all tests? Because at a glance, it doesn’t seem to me like this would give accurate Roman numerals because it doesn’t appear to consider how IV, IX, XL, etc. are handled. That is, if I gave it 4, I would expect IIII, which is not correct.
Yes, it passed all the tests, and i checked before submitting in VSCode with Quokka, everything seemed ok, the only problem was with the last test (3999), which was starting with MCM instead of MM, that’s why i added the 2000 key.
Ah I see, I scanned your map too quickly. You accounted for IV, IX, etc. in the map itself. So it works. The other approach is to leave out those and just code I,V,X,etc in the array and do an algorithm that recognizes when the number is “one less than” and converts that (i.e., from IIII -> IV). That would be a slightly smaller map/array/object and slightly more scaleable version (i.e., easier to add more numbers to as you don’t have to worry about hard-entering the “one less than” case into your map/array/object.
1 Like
It would be nice to have the code instead of an image. Anyway, you should be able to get rid of the ones that are just the same number twice (XX, DD, MM)
This is passing the tests but to be honest I didn’t really think about the code much so maybe there are issues with it I didn’t consider.
function convertToRoman(num) {
var result = [];
var numerals = new Map([
[1000, 'M'],
[900, 'CM'],
[500, 'D'],
[400, 'CD'],
[100, 'C'],
[90, 'XC'],
[50, 'L'],
[40, 'XL'],
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I'],
]);
numerals.forEach((value, key) => {
while (num >= key) {
result.push(value);
num -= key;
}
});
return result.join('');
}
1 Like
This is long and painful in structure but does use a shorter input array.