intelligently generating combinations of combinations

后端 未结 4 1346
遇见更好的自我
遇见更好的自我 2021-01-19 15:23

Let\'s say I have a class of 30 students and want generate every possible way in which they can be partitioned into groups of 5 (order is irrelevant).

I know how to

4条回答
  •  无人共我
    2021-01-19 16:04

    This is an old question, but anyway, for the record, that's how I would it in Ruby:

    class Array
      def groups_of_size(n)
        Enumerator.new do |yielder|
          if self.empty?
            yielder.yield([])
          else
            self.drop(1).combination(n-1).map { |vs| [self.first] + vs }.each do |values|
              (self - values).groups_of_size(n).each do |group|
                yielder.yield([values] + group)
              end   
            end
          end
        end
      end
    end
    

    I use an enumerator because the output can grow very quickly, a strict output (an array for example) wouldn't be useful. A usage example:

    >> pp [0, 1, 2, 3, 4, 5].groups_of_size(3).to_a
    => 
    [[[0, 1, 2], [3, 4, 5]],
     [[0, 1, 3], [2, 4, 5]],
     [[0, 1, 4], [2, 3, 5]],
     [[0, 1, 5], [2, 3, 4]],
     [[0, 2, 3], [1, 4, 5]],
     [[0, 2, 4], [1, 3, 5]],
     [[0, 2, 5], [1, 3, 4]],
     [[0, 3, 4], [1, 2, 5]],
     [[0, 3, 5], [1, 2, 4]],
     [[0, 4, 5], [1, 2, 3]]]
    

提交回复
热议问题