解析字符串中的数字

时间:2017-05-04 01:11:50

标签: ruby algorithm parsing

我试图让我的代码通过此测试。如果你曾经在这次聚会中扮演魔法,这对你来说可能很熟悉。

    Test.assert_equals(can_cast("11RB","10B","1R"), true)
    Test.assert_equals(can_cast("13BBRR","10BR","2R","B"), true)

但我似乎无法正确解析元素中的正确数字。有没有人看到我的代码中有一个缺陷导致我不能通过这些测试?

def can_cast(hand, *spell_cost)
  colored_mana_hand = Array.new
  colored_mana_cost_aggregate = Array.new
  colored_mana_spent = Array.new

  colorless_mana_hand_array = []
  colorless_mana_hand = 0

  colorless_mana_cost_array = []
  colorless_mana_cost_aggregate_array = []
  colorless_mana_cost_aggregate = 0


  hand.split("").each do |i|
    if i.to_i != 0                        # extracting existing colorless mana from hand
    colorless_mana_hand_array << i
    else
    colored_mana_hand << i
    end
  end
  colorless_mana_hand = colorless_mana_hand_array.join.to_i

  spell_cost.each do |i|                   # extracting existing colorless mana from cost
    i.split("").each do |j|
      if j.to_i != 0                  
      colorless_mana_cost_array << j
    else
      colored_mana_cost_aggregate << j
    end
    end
      colorless_mana_cost_aggregate_array << colorless_mana_cost_array.join
      colorless_mana_cost_array.clear
  end

    colorless_mana_cost_aggregate_array.each do |i|
    colorless_mana_cost_aggregate += i.to_i
  end

    colored_mana_cost_aggregate.each do |i|                                                  # pay colored mana first
     if colored_mana_hand.include?(i)
       colored_mana_spent << i
       colored_mana_hand.rotate(colored_mana_hand.index(i)).shift
     end
  end

  (colored_mana_spent.sort == colored_mana_cost_aggregate.sort) && (colored_mana_hand.length + colorless_mana_hand) >= colorless_mana_cost_aggregate 
end 

2 个答案:

答案 0 :(得分:1)

这是一种从字符串中提取数字的有趣方法。它可能更容易使用scan,以下是如何使用它:

# extracting existing colorless
colorless_mana_hand_array = hand.scan(/\d/).join.to_i

这会将字符串中的数字提取到数组中,连接它们,然后转换为整数。

答案 1 :(得分:0)

  

有没有人在我的代码中看到一个阻止我通过这些测试的缺陷?

是的,的确如此。

您通过以下方式分割spell_cost字符串:

i.split("").each do |j|
  # ...
end

代码将为块生成每个单个字符。对于"10BR",这给出了:

"10BR".split("").each do |j|
  p j: j
end

输出:

{:j=>"1"}
{:j=>"0"}
{:j=>"B"}
{:j=>"R"}

此外,你有这个检查:

if j.to_i != 0
  colorless_mana_cost_array << j
else
  colored_mana_cost_aggregate << j
end

对于上述输入,您将获得

colorless_mana_cost_array   #=> ["1"]
colored_mana_cost_aggregate #=> ["0", "B", "R"]

因为"0".to_i != 0评估为false,就像"B""R"一样。

如果我正确理解您的代码,"0"应该进入colorless_mana_cost_array