Skip to content

Instantly share code, notes, and snippets.

@codebubb
Created November 25, 2015 13:19
Show Gist options
  • Save codebubb/48553a17a594175f60da to your computer and use it in GitHub Desktop.
Save codebubb/48553a17a594175f60da to your computer and use it in GitHub Desktop.
// Bonfire: Roman Numeral Converter
// Author: @codebubb
// Challenge: http://www.freecodecamp.com/challenges/bonfire-roman-numeral-converter?solution=%2F%2F%20Flow%20for%20conversion%3A%20http%3A%2F%2Fwww.rapidtables.com%2Fconvert%2Fnumber%2Fhow-number-to-roman-numerals.htm%20%0Avar%20vals%20%3D%20%7B1%20%3A%20%27I%27%2C%204%3A%20%27IV%27%2C%205%3A%20%27V%27%2C%209%3A%20%27IX%27%2C%2010%3A%20%27X%27%2C%2040%3A%20%27XL%27%2C%2050%3A%20%27L%27%2C%2090%3A%20%27XC%27%2C%20100%3A%20%27C%27%2C%20400%3A%20%27CD%27%2C%20500%3A%20%27D%27%2C%20900%3A%20%27CM%27%2C%201000%3A%20%27M%27%7D%3B%0Afunction%20convert(n)%7B%0A%09var%20roman%20%3D%20%22%22%3B%0A%09while(n%3E0)%7B%0A%09%09%2F%2F%20find%20highest%20decimal%0A%09%09var%20v%20%3D%20findHighest(n)%3B%0A%09%09%2F%2F%20write%20roman%20numeral%0A%09%09roman%20%2B%3D%20vals%5Bv%5D%3B%0A%09%09%2F%2F%20subtract%20highest%20decimal%20from%20total%20number%0A%09%09n%20-%3D%20v%3B%0A%09%7D%0A%09return%20roman%3B%0A%7D%0A%0Afunction%20findHighest(n)%7B%0A%09var%20decimals%20%3D%20Object.keys(vals).reverse()%3B%0A%09for(k%20in%20decimals)%7B%0A%09%09if%20(n%20%3E%3D%20decimals%5Bk%5D)%20return%20decimals%5Bk%5D%3B%0A%09%7D%0A%09return%200%3B%09%0A%7D%0A%0Aconsole.log(convert(1984))%3B
// Learn to Code at Free Code Camp (www.freecodecamp.com)
// Comments:
// Struggled with this one, I think there is a better way to do this programatically e.g. work out if a IV should be added for a 4 instead of 4 x I
// Quite happy with solution although I don't think it can be refactored any more <- I think using an array (or object) is unavoidable if the above approach is not taken.
// Flow for conversion: http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm
var vals = {1 : 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'};
function convert(n){
var roman = "";
while(n>0){
// find highest decimal
var v = findHighest(n);
// write roman numeral
roman += vals[v];
// subtract highest decimal from total number
n -= v;
}
return roman;
}
function findHighest(n){
var decimals = Object.keys(vals).reverse();
for(k in decimals){
if (n >= decimals[k]) return decimals[k];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment