Skip to content

Instantly share code, notes, and snippets.

@zacharytamas
Last active September 6, 2018 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacharytamas/c396833b8f821c29fd1bce9fd9db511d to your computer and use it in GitHub Desktop.
Save zacharytamas/c396833b8f821c29fd1bce9fd9db511d to your computer and use it in GitHub Desktop.
There are so many ways to convert Roman numerals
const convertValueToSymbol = (() => {
const SYMBOLS = {
1000: 'M',
500: 'D',
100: 'C',
50: 'L',
10: 'X',
5: 'V',
1: 'I'
};
return (value, placeValue) => {
const symbol = SYMBOLS[placeValue];
const higherSymbol = SYMBOLS[placeValue * 10];
const midSymbol = SYMBOLS[(placeValue * 10) / 2];
return (value === 9
? [symbol, higherSymbol]
: value >= 5
? [midSymbol, convertValueToSymbol(value - 5, placeValue)]
: value === 4
? [symbol, midSymbol]
: [symbol.repeat(value)]
).join('');
};
})();
export const solution = number =>
Array
// Create an array of the individual digits in the provided
// number so that we can work on them one-by-one.
.from(number.toString())
// For each digit, also calculate its place value in the original
// number and return them as a 2-tuple.
.map((item, index, array) =>
// The exponent is calculated by determining our current
// position in the array compared to how many elements are in
// it. Note that in the case of the last element this
// evaluates to 0, making the whole exponential expression
// equal to 1 (R^0 = 1 axiomatically)
[Number(item), Math.pow(10, array.length - index - 1)]
)
.map(tuple => convertValueToSymbol(...tuple))
// Now concatenate all symbols into a single string.
.join('');
export const solution2 = (() => {
// Just a shortened notation that evaluates to an array of arrays
// containing the denomination values and their symbol.
const DENOMINATIONS = `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`
.split(' ')
.map(pair => pair.split(':'));
return number => {
let value = number;
const symbols = [];
for (const [symbolValue, symbol] of DENOMINATIONS) {
const count = Math.floor(value / Number(symbolValue));
value -= Number(symbolValue) * count;
symbols.push(symbol.repeat(count));
}
return symbols.join('');
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment