Monday, July 27, 2020

Roman Numeral Converter

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter

const ROMAN_NUMERALS = Object.freeze({
    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'
});

function convertToRoman(num) {
    const digit = Math.max(...Object.keys(ROMAN_NUMERALS).filter(key => num >= key));
    if (num === digit) {
        return ROMAN_NUMERALS[digit];
    }
    return ROMAN_NUMERALS[digit] + convertToRoman(num - digit);
}

[
    2,
    3,
    4,
    5,
    9,
    12,
    16,
    29,
    44,
    45,
    68,
    83, 
    97,
    99,
    400,
    500,
    501,
    649,
    798,
    891,
    1000,
    1004,
    1006,
    1023, 
    2014,
    3999
].forEach(arg => console.log(arg, convertToRoman(arg)));

Output:
2 II
3 III
4 IV
5 V
9 IX
12 XII
16 XVI
29 XXIX
44 XLIV
45 XLV
68 LXVIII
83 LXXXIII
97 XCVII
99 XCIX
400 CD
500 D
501 DI
649 DCXLIX
798 DCCXCVIII
891 DCCCXCI
1000 M
1004 MIV
1006 MVI
1023 MXXIII
2014 MMXIV
3999 MMMCMXCIX

Another approach:
const ROMAN_NUMERALS = Object.freeze({
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1
})


function convertToRoman(num) {
    let rn = '';
    for (const [rnLetter, rnValue] of Object.entries(ROMAN_NUMERALS)) {
        const q = Math.trunc(num / rnValue);
        rn += rnLetter.repeat(q);
        num -= q * rnValue;
    }
    return rn;
}


[
    2,
    3,
    4,
    5,
    9,
    12,
    16,
    29,
    44,
    45,
    68,
    83, 
    97,
    99,
    400,
    500,
    501,
    649,
    798,
    891,
    1000,
    1004,
    1006,
    1023, 
    2014,
    3999
].forEach(arg => console.log(arg, convertToRoman(arg)));


Output:
2 II
3 III
4 IV
5 V
9 IX
12 XII
16 XVI
29 XXIX
44 XLIV
45 XLV
68 LXVIII
83 LXXXIII
97 XCVII
99 XCIX
400 CD
500 D
501 DI
649 DCXLIX
798 DCCXCVIII
891 DCCCXCI
1000 M
1004 MIV
1006 MVI
1023 MXXIII
2014 MMXIV
3999 MMMCMXCIX

No comments:

Post a Comment