The challenge
Write toRoman(n) for whole numbers from 1 to 3999. The symbols are M=1000, D=500, C=100, L=50, X=10, V=5, I=1, and the special pairs CM=900, CD=400, XC=90, XL=40, IX=9, IV=4.
toRoman(4) // "IV"
toRoman(1969) // "MCMLXIX"
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
toRoman(3)gives"III"toRoman(4)gives"IV"toRoman(1969)gives"MCMLXIX"toRoman(2024)gives"MMXXIV"toRoman(3999)gives"MMMCMXCIX"
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Make a list of [value, symbol] pairs from biggest to smallest, including the special pairs.
Hint 2
For each pair: while n is at least the value, add the symbol and subtract the value.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function toRoman(n) {
const table = [[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"]];
let result = "";
for (const [value, symbol] of table) {
while (n >= value) {
result += symbol;
n -= value;
}
}
return result;
}
Learn what you need
This exercise uses what Grade 10: Array Power Tools: map, filter & reduce teaches. Read those notes first if any of it is new.