Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active August 29, 2015 14:27
Show Gist options
  • Save epitron/1e0a519c5bb28b6320fa to your computer and use it in GitHub Desktop.
Save epitron/1e0a519c5bb28b6320fa to your computer and use it in GitHub Desktop.
BASIC_NUMERALS = {
1000 => "M",
500 => "D",
100 => "C",
50 => "L",
10 => "X",
5 => "V",
1 => "I",
}
NUMERAL_VALUES = BASIC_NUMERALS.keys.sort.reverse
# if the number is greater than half way, subtract from the larger numeral
# if the number is less than half way, then add to the smaller numeral
def roman(n, max=0)
if numeral = BASIC_NUMERALS[n]
numeral
else
i = NUMERAL_VALUES.index { |val| n >= val }
smaller = NUMERAL_VALUES[i]
bigger = NUMERAL_VALUES[i-1]
# p smaller: smaller, bigger: bigger
if n == bigger - 1
roman(bigger - n, i) + roman(bigger)
else
roman(smaller, i) + roman(n - smaller, i)
end
end
end
# Bugs:
# - You can only subtract ONE number from another.
# - "Groups" of numerals (sets of numerals that end up being added together) must be ordered from largest to smallest.
(1..50).each do |n|
puts "#{n}: #{roman(n)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment