Ruby数组没有循环两次?

时间:2015-08-16 17:03:34

标签: arrays ruby

我有一个数组数组。我试图遍历主数组中的每个数组,并将索引与变量进行比较。如果它们大于我想要从父数组中删除该数组的变量。在我与b进行比较时运行以下代码的那一刻,它第一次运行并删除数组但似乎没有再次运行并删除其中索引>的其余数组。湾任何帮助表示赞赏。

以下功能应打印14但目前正在打印16。

a = 4
b = 2
c = 5
n = 5

def count_configurations(a, b, c, n)

  a = (0..a).to_a
  b = (0..b).to_a
  c = (0..c).to_a

  big = [a.max, b.max, c.max].max
  big = (0..big).to_a

  arrays = big.repeated_permutation(3).to_a

  solutions = []

  arrays.each do |array|
    sum = 0
    array.each { |a| sum+=a }

    if sum == n 
      solutions << array
    end
  end

  solutions = solutions.uniq

  solutions.each do |solution|
    if solution[0] > a.max 
      solutions.delete(solution)
    end
  end

  solutions.each do |solution|
    if solution[1] > b.max 
      solutions.delete(solution)
    end
  end

  solutions.each do |solution|
    if solution[2] > c.max 
      solutions.delete(solution)
    end
  end

  puts solutions.count
end

1 个答案:

答案 0 :(得分:2)

假设solutions包含正确的数组,请转到此处,而不是三个each循环:

solutions = solutions.uniq.reject do |solution|
  solution[0] > a.max || solution[1] > b.max || solution[2] > c.max 
end

详细信息:Enumerable#reject