Created
April 4, 2013 07:44
-
-
Save snorremd/5308578 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment