【问题标题】:When / How to stop Ruby loop that creates nested arrays within nested arrays何时/如何停止在嵌套数组中创建嵌套数组的 Ruby 循环
【发布时间】:2015-08-21 00:21:02
【问题描述】:

我不确定何时结束运行 map 语句的循环,时间只是作为示例说明循环应该在哪里以及应该包含哪些代码。我想运行它,直到创建的多维数组的第一个值为 0(因为它始终是最大值,直到它本身变为 0 并创建最后一个嵌套数组),但我完全不知道该怎么做.任何帮助将不胜感激!

def wonky_coins(n)
    coins = [n]
    if n == 0
        return 1
    end
    i = 1
    n.times do 
        coins.map! do |x|
        if x != 0
            i+= 2 
        else
            next
        o = []    
        o << x/2 
        o << x/3 
        o << x/4
        x = o
        puts x
        end
        end
    end
        return i
end

wonky_coins(6)

问题:

# Catsylvanian money is a strange thing: they have a coin for every
# denomination (including zero!). A wonky change machine in
# Catsylvania takes any coin of value N and returns 3 new coins,
# valued at N/2, N/3 and N/4 (rounding down).
#
# Write a method `wonky_coins(n)` that returns the number of coins you
# are left with if you take all non-zero coins and keep feeding them
# back into the machine until you are left with only zero-value coins.
#
# Difficulty: 3/5

describe "#wonky_coins" do
  it "handles a coin of value 1" do
    wonky_coins(1).should == 3
  end

  it "handles a coin of value 5" do
    wonky_coins(5).should == 11
    # 11
    # => [2, 1, 1]
    # => [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
    # => [[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]]
  end

  it "handles a coin of value 6" do
    wonky_coins(6).should == 15
  end

  it "handles being given the zero coin" do
    wonky_coins(0).should == 1
  end
end

【问题讨论】:

  • 要停止循环,您只需使用break 命令。要跳到下一个元素而不停止整个过程,请使用next 命令。

标签: arrays ruby loops


【解决方案1】:

首先,您不应该有嵌套数组。你想在每次通过后展平阵列,所以你只有硬币;更好的是,使用flat_map 一步完成。 0 自己产生:[0];不要忘记它,否则您的代码将丢失所有目标硬币!

接下来,我可以看到n 次没有逻辑。没有固定数量的times 可以。你想做until所有硬币都是零。您可以在顶部设置一个标志 (all_zero = true),并在找到非零硬币时翻转它,这应该告诉您的循环需要进一步的迭代。

此外,您不需要跟踪硬币的数量,因为该数字将是数组的最后一个 size

最后,与问题无关,养成使用正确缩进的习惯。一方面,它使您自己更难调试和维护代码;另一方面,糟糕的缩进让许多 SO 人不想费心阅读您的问题。

【讨论】:

    【解决方案2】:

    现在知道如何使用 .flatten 后回去了,我明白了!感谢@Amadan 提供有用的提示。请随意留下任何关于我的语法的 cmets,因为我刚刚开始并且可以使用我可以获得的所有建设性反馈!

    def wonky_coins(n)
        coins = [n]
        return 1 if n == 0
        until coins[0] == 0
            coins.map! { |x|
                next if x == 0 
                x = [x/2, x/3, x/4]
            }
            coins.flatten!
        end
        return coins.length
    end
    
    wonky_coins(6)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多