public
Created

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.

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
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!"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.