Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Last active May 17, 2019 12: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 A1rPun/4ca5be3cce5f027ff42138c4dfa5b31e to your computer and use it in GitHub Desktop.
Save A1rPun/4ca5be3cce5f027ff42138c4dfa5b31e to your computer and use it in GitHub Desktop.
A function to convert a number to a roman numeral

Roman numerals

1..toRoman() // "I"
18..toRoman() // "XVIII"
1910..toRoman() // "MCMX"
9999..toRoman() // "MMMMMMMMMCMXCIX"

Inspiration

const romanNumerals = [
["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], // ones
["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], // tens
["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], // hundreds
];
Number.prototype.toRoman = function() {
return this
.toString()
.split("")
.reverse()
.reduce((acc, x, i) => (i < 3 ? romanNumerals[i][x] : "M".repeat(x)) + acc, "");
};
String.prototype.toRomanNumeral = function() {
let str = this;
const sortLength = (a, b) => b.length - a.length;
const numeral = romanNumerals.reduce((acc, x) => {
const check = x.filter(y => ~str.indexOf(y)).sort(sortLength)[0];
if (check) str = str.slice(0, -check.length);
return x.indexOf(check) + acc;
}, '');
return parseInt(numeral, 10) + str.match(/^M*/)[0].length * 1000;
}
using System;
using System.Collections.Generic;
using Linq;
// This function needs testing!
public static string ToRoman (int n) {
var romanNumerals = new string[][] {
new string[] { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, // ones
new string[] { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, // tens
new string[] { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }, // hundreds
};
// This needs more chaining
var chars = new List<char>();
chars.AddRange(n.ToString());
chars.Reverse();
chars.Aggregate((acc, x, i) => (i < 3 ? romanNumerals[i][Int32.Parse(x)] : new String ('M', Int32.Parse(x))) + acc, "");
return String.Join("", chars);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment