罗马数字解码器:Ruby

时间:2020-09-10 10:08:01

标签: ruby string algorithm parsing

好的,我已经在编码挑战方面工作了一段时间了,我想现在是正式升起国旗的时候了。救命!

我的任务是创建一个函数,该函数以罗马数字作为参数,并以数字十进制整数形式返回其值。

到目前为止,我已经成功创建了一个将数字映射为其数值的哈希。我还创建了一个空数组roman_no来传递键/值对。

我正在努力写的是表达式。下面是完整的代码:

def solution(roman)
 # take a value of a roman numeral 
 roman_numeral =
    {
      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" 
      }

roman_no = Array.new
  
roman_numeral.each do | key, value | 
  while 
    "#{roman}" >= "#{key}"
      += roman_no 
    "#{roman}" -= "#{key}"
    end
  
return roman_no

  
 
solution('XXI')

我如何编写一个参数,该参数将从roman_numeral中获取值并返回其数字计数器部分?

例如:

solution('XXI') # should return 21

1 个答案:

答案 0 :(得分:3)

def solution(roman)
  mapping = {
     "M"=>1000,
     "D"=>500,
     "C"=>100,
     "L"=>50,
     "X"=>10,
     "V"=>5,
     "I"=>1
  }
  # split string into characters
  roman.chars.map do |l|
    mapping[l] # replace character with integer value
  end
  .compact # removes potential nils caused by  invalid chars
  # Splits array into chunks so that we can handle numerals such as IIX
  .chunk_while do |i,j|
    i <= j #
  end
  # each chunk will be an array like [10, 10, 100] or [1, 1, 1, 1]
  .map do |chunk| 
    if chunk.first < chunk.last
      chunk.reverse.inject(:-) # handles numerals such as IIX with subtraction
    else
      chunk.sum # chunk is just a list of numerals such as III
    end
  end
  .sum # sums everything up
end