Search code examples
arraysrubyhashroman-numerals

Roman Number Calculator


I have to make an assignment wherein I have to implement the Roman Numerals along with the rules that are followed while doing calculations on them, contained in this link

http://www.periodni.com/roman_numerals_converter.html

I don't want the code, just help. I have gone with two approaches till now:

  1. Using constants, I have declared the roman numerals as constants, and then after getting the input, I am left with the choice to decode the string input, which I later dropped.
  2. Using hash. I have declared a hash with the numerals, then after getting the input, I am converting the string using to_sym method into there corresponding value. After this, I have taken an array containing the decimals of the roman numerals, and I intend to compare those with the input. I am stuck at this part. I don't know how to compare here. Also, I don't want to sort the input array, because then calculations would go wrong.

Can anyone help me with how to proceed? Not the code, just steps.

This is what I have done so far:

class Conversion
  hash ={ :I => 1, :V => 5, :X => 10, :L => 50, :C => 100, :D => 500, :M => 1000}
  result = 0
  value = []
  hash_values = hash.values

  puts "enter input string"
  input = gets.chomp.upcase.split(//)

  input.each do |i|
    value <<  hash[i.to_sym]
  end

  for i in value do
    if value[i] > value[i+1]
      result = result + value[i]
    else
      result = result + (value[i+1] - value[i])
    end
  end

  puts result
end

If u run the code, you'll see that while I try to compare in the last loop it is taking the index for calculations. Same happened when I tried doing the same using two hashes. I can't use any gem or external libraries cause that is the requirement.


Solution

  • The idea is to create a tree where every node have two childrens: the left one is what to substract and the right one is what to add.

    Once you get a string, you find the most valued letter and make it the first node like this:

      XLIX
    
        L
       / \
      X   IX
    

    Then you run this function recursively on the children nodes until the node is trivial (like XX or III).

    The final step is to recursively calculate the result.