Skip to content

Instantly share code, notes, and snippets.

@efrenfuentes
Last active June 10, 2016 20:46
Show Gist options
  • Save efrenfuentes/56b7333666c2e474f249eb958cd7e215 to your computer and use it in GitHub Desktop.
Save efrenfuentes/56b7333666c2e474f249eb958cd7e215 to your computer and use it in GitHub Desktop.
Romans
# Roman numbers values
ROMAN_VALUES = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I"
}
def roman_to_integer(str = self, result = 0)
# return 0 if string is empty
return result if str.empty?
# check if string start with a roman value
ROMAN_VALUES.values.each do |roman|
if str.start_with?(roman) # start with roman value
result += ROMAN_VALUES.invert[roman] # add value to result
str = str.slice(roman.length, str.length) # delete roman processed from string
return roman_to_integer(str, result) # recursive call to process the rest of string
end
end
end
# Read file
text = File.open("#{ARGV[0]}").read.split
# for each line convert roman to integer
text.each do |roman|
puts "#{roman} => #{roman_to_integer(roman)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment