罗马数字解码器:Ruby [英] Roman Numerals Decoder: Ruby

查看:48
本文介绍了罗马数字解码器:Ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Alright I've been working on this coding challenge for quite some time and I guess it's officially time for me to raise the flag. Help!

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

My task is to create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.

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

So far I've successfully created a hash mapping the numbers to its numeric values. I've also created an empty array roman_no to pass the key/value pair through.

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

What I am struggling with is writing the expression. Below is the full code:

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 中获取值并返回其数字计数器部分?

How can I write an argument that will take the value from roman_numeral and return its number counter part?

例如:

solution('XXI') # should return 21

推荐答案

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

这篇关于罗马数字解码器:Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆