Hi
I have been plodding through the Intermediate Algorithm challenges and every time I solve one I always check what the provided solution was in “Get a Hint” to see if I went the same way about approaching the problem.
Most of the time, the solutions are more elegant than mine, however on the Roman Numeral Project, I used a RegExp function which I feel is a more logical approach than the solutions.
Code (with notes):
function convertToRoman(num) {
//Define Lists to store initial split, regex lookups and replacements
let li = [];
let findList = [
/IIIII/g, /IIII/g, /VV/g, /VIV/g, /XXXXX/g, /XXXX/g, /LL/g, /LXL/g, /CCCCC/g, /CCCC/g, /DD/g, /DCD/g,]
let replaceList = [
"V", "IV", "X", "IX", "L", "XL", "C", "XC", "D", "CD", "M", "CM",];
//Define the replacement function with arguments for find, replace.
let reg = function(find, replace) {
li = li.replace(find, replace)
}
//break your initial argument to a list of the smallest unit "I"
//eg 5 => ["I", "I", "I", "I", "I"]
for (let i = 0; i < num; i++) {
li.unshift("I")
};
//Join it back to a string ready for our RegExp function
li = li.join("");
//Iterate through the find list, replacing larger and larger denominations
//eg replace all instances of "IIIII" with "V", then "IIII" with "IV" etc.
for (let i = 0; i< findList.length; i++) {
reg(findList[i], replaceList[i]);
}
return li
}
convertToRoman(3999);
My question is in the title - Is there such a thing as a “Wrong Solution” providing the code works?
For a challenge like this I know its not a huge deal, but for those who are working in a coding job - is this something you keep in mind when working & how does it affect your design choices?
Thank you for reading