Skip to content

Instantly share code, notes, and snippets.

@crazymykl
Created January 20, 2016 20:04
Show Gist options
  • Save crazymykl/cb7a691944ed52f2c277 to your computer and use it in GitHub Desktop.
Save crazymykl/cb7a691944ed52f2c277 to your computer and use it in GitHub Desktop.
DIGIT_VALUES = {
'I' => 1,
'IV' => 4,
'V' => 5,
'IX' => 9,
'X' => 10,
'XL' => 40,
'L' => 50,
'XC' => 90,
'C' => 100,
'CD' => 400,
'D' => 500,
'CM' => 900,
'M' => 1000,
}
SORTED_DIGIT_VALUES = DIGIT_VALUES.sort_by { |_roman, arabic| arabic }.reverse
TOKENIZER = Regexp.union(*SORTED_DIGIT_VALUES.map(&:first))
def tokenize(roman)
roman.scan TOKENIZER
end
def roman2arabic(roman)
tokenize(roman).map { |r| DIGIT_VALUES[r] }.reduce(0, :+)
end
def arabic2roman(arabic)
''.tap { |roman|
SORTED_DIGIT_VALUES.each do |symbol, value|
while arabic >= value
roman << symbol
arabic -= value
end
end
}
end
def multiply_roman(*args)
arabic2roman args.map { |a| roman2arabic a }.reduce(1, :*)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment