如何生成数组组合,以便数组中的两个元素不能在任何组合中组合在一起

时间:2015-04-27 13:59:08

标签: ruby-on-rails ruby

假设我有一个包含五个元素['a','b','c','d','e']的数组。我想要四个元素的组合,但我希望'a''b' 不能在任何组合中组合在一起。我该怎么做?

预期结果应该是 ['a', 'c', 'd', 'e'] ['b', 'c', 'd', 'e']

请写一个更通用的解决方案。我正在使用ruby的combination方法。我这里只是写一个例子。组合数可能会有所不同(比如可能有一个数组) 9,大小为7种组合)并且我可能需要两个元素说aedf不应该在任何组合中。我知道这有点令人困惑,如果我需要解释,请告诉我。真的很感激任何帮助。

2 个答案:

答案 0 :(得分:2)

['a','b','c','d','e'].permutation(4).reject do |e| 
  e.include?('a') && e.include?('b')
end

或者,如果您不关心元素顺序(@ mark-thomas的学分),请使用Array#combination

['a','b','c','d','e'].combination(4).reject do |e| 
  e.include?('a') && e.include?('b')
end
#⇒ [["a", "c", "d", "e"], ["b", "c", "d", "e"]]

请注意,这种方法渴望获得资源。我不建议在大阵列上使用它。

答案 1 :(得分:-1)

我认为你正在寻找类似的东西:

def combine(array, should_not_be_together, size)
  aux          = []
  add_together = true

  while aux.size < size
    random = Random.rand(2)
    if random == 1
      aux << array.sample
    elsif add_together
      aux << should_not_be_together.sample
      add_together = false
    end

    aux.uniq!
  end

  aux
end

array                  = ['c', 'd', 'e']
should_not_be_together = ['a', 'b']
size                   = 4
combine(array, should_not_be_together, size)

结果:

# => ["c", "a", "d", "e"]
# => ["e", "b", "c", "d"]
# => ["e", "a", "c", "d"]
# => ["c", "d", "b", "e"]
# => ["d", "b", "e", "c"]
# => ["a", "c", "e", "d"]
# => ["c", "b", "d", "e"]
# => ["c", "a", "e", "d"]