Sunday, June 13, 2021

Javascript Practice 77: JS Hero - Roman numerals I

 
Question: 

Write a function arabic that converts a Roman number (up to 1000) into an Arabic.

Example: arabic('CDLXXXIII') should return 483.





Answer: 

function arabic (s) {

let romanObj = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; 
let arabicArr = []; 

for (let i = 0; i < s.length; i++) {

if (romanObj[s[i]] < romanObj[s[i+1]]) {

arabicArr.push(romanObj[s[i+1]] - romanObj[s[i]]); 
i++; 
continue;
} else {arabicArr.push(romanObj[s[i]]);}

}
return arabicArr.reduce((acc,cv) => acc + cv);
}




> we declare a function ‘arabic’
> it has one parameter ‘s’ 
> we declare another variable ‘romanObj’ 
> we initialize it with roman numerals and their values in ‘key: value’ format
> like this: {I:1, V:5, X:10, etc}
> thus we make the variable ‘romanObj’ an object; that holds multiple values in terms of properties and methods
> we also declare another variable ‘arabicArr’ , it is an empty array, like this: ‘ [] ‘
> we leave it empty; it will be used to push the value we get while processing the code in the function ‘arabic’
> we open a ‘for loop’ to process the function ‘arabic’, where we want to convert the roman numerals into integers or ‘arabic’
> the ‘for loop’ will go through the string ‘ s ‘, one element at a time; like this: ‘III’ – [ ‘I’, ‘I’, ‘I’ ] 
> inside the ‘for loop’ we test if our first roman numeral is less than the second roman numeral, for eg: ‘IV’
> where I = 1 && V = 5
> so we want to take the string ‘s’ value at that index and compare it to the values provided in the ‘romanObj’ variable
> if the strings ‘s’ value at the index is greater than the consecutive index value then we want to subtract it from the consecutive index value
> like this: 5 – 1 = 4; 
> we then want to push it to the array ‘arabicArr’ variable
> we then push the iteration up by i++ and then we break out of the iteration of the for loop by using ‘continue’
> if it is not greater than we want it to be pushed inside the ‘arabicArr’ variable
> once the for loop has gone through all the values then we want to return the ‘arabicArr’ array
> since we want the result to be returned in integers, we want the sum of all values of the array ‘arabicArr’ 
> so we use the reduce function, with the accumulator adding all the current values of the ‘arabicArr’  array
 




No comments:

Post a Comment