Instantly share code, notes, and snippets.

# snorremd/gist:5308578 Created Apr 4, 2013

What would you like to do?
Authors: Lisa, Snorre A quick and simple solution for converting from decimal numbers to roman numerals. It is based on a table (double array) lookup-algorithm using a digit's position in a number as well as its value to find the correct roman numeral to add to the roman numeral string/array.
 class NumeralRomanConverter def initialize @romanTable = [ ["I","IV","V","IX"], ["X","XL","L","LC"], ["C","LC","D","CM"], ["M"]] end def numeralToRoman(numeralValue) numberAsString = numeralValue.to_s numberAsString.reverse! romanNumeral = Array.new for i in 0..numberAsString.size value = numberAsString[i].to_i romanNumeral.unshift(getRomanNumeral(i+1,value)) end romanNumeralString = "" for i in 0..romanNumeral.size-1 romanNumeralString += romanNumeral[i] end puts numeralValue.to_s + " is " + romanNumeralString end def getRomanNumeral(digitNumber, value) digitPos = digitNumber-1 romanNumerals = "" if value <= 3 for i in 1..value romanNumerals += @romanTable[digitPos][0] end elsif value == 4 romanNumerals += @romanTable[digitPos][1] elsif value == 5 romanNumerals += @romanTable[digitPos][2] elsif value <= 8 romanNumerals += @romanTable[digitPos][2] for i in 6..value romanNumerals += @romanTable[digitPos][0] end else romanNumerals += @romanTable[digitPos][3] end return romanNumerals end end converter = NumeralRomanConverter.new converter.numeralToRoman(54) converter.numeralToRoman(100) converter.numeralToRoman(2999) puts "Try your own numbers! (Type 'exit' to quit the program).." input = "" begin input = gets.chomp converter.numeralToRoman(input.to_i) end while input != "exit" puts "Good bye!"