0

I have:

@pakker[0] = 6

@number = [1, 2, 3, 4, 5, 6]

(1..@pakker[0]).map {|i| @number.map{|d| d}.combination(i).to_a}

In my console:

<r[0]).map {|i| @number.map{|d| d}.combination(i).to_a}
=> [[[1], [2], [3], [4], [5], [6]], [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2,
 3], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6], [5, 6]], [[
1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [1,
4, 5], [1, 4, 6], [1, 5, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4,
6], [2, 5, 6], [3, 4, 5], [3, 4, 6], [3, 5, 6], [4, 5, 6]], [[1, 2, 3, 4], [1, 2
, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 5, 6], [1, 3, 4, 5], [
1, 3, 4, 6], [1, 3, 5, 6], [1, 4, 5, 6], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 5, 6
], [2, 4, 5, 6], [3, 4, 5, 6]], [[1, 2, 3, 4, 5], [1, 2, 3, 4, 6], [1, 2, 3, 5,
6], [1, 2, 4, 5, 6], [1, 3, 4, 5, 6], [2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6]]]
irb(main):165:0>

Instead I don't want all these arrays instead I want something like:

=> [1, 2, 3, 4, 5, 6, [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], etc. 

How do I remove all those arrays in arrays?

I have tried flatten:

<r[0]).map {|i| @number.map{|d| d}.combination(i).to_a}.flatten(1)
=> [[1], [2], [3], [4], [5], [6], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 3]
, [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6], [5, 6], [1, 2,
 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [1, 4, 5]
, [1, 4, 6], [1, 5, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6], [
2, 5, 6], [3, 4, 5], [3, 4, 6], [3, 5, 6], [4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 5]
, [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 5, 6], [1, 3, 4, 5], [1, 3, 4
, 6], [1, 3, 5, 6], [1, 4, 5, 6], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 5, 6], [2,
4, 5, 6], [3, 4, 5, 6], [1, 2, 3, 4, 5], [1, 2, 3, 4, 6], [1, 2, 3, 5, 6], [1, 2
, 4, 5, 6], [1, 3, 4, 5, 6], [2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
irb(main):197:0>
Rails beginner
  • 14,321
  • 35
  • 137
  • 257
  • Looking for [this?][1] [1]: http://stackoverflow.com/questions/8533336/generate-a-powerset-of-a-set-without-keeping-a-stack-in-erlang-or-ruby – steenslag Jan 15 '12 at 23:23
  • @steenslag Not exactly, you'd still need to remove one level of array-ification after collecting the lazy enumeration. Ultimately it's the same thing, although it assumes you're actually looking for a powerset--the OP's post is, but it's not stated that *n* will necessarily equal the length of the array. It could certainly be modified to take *n* as an argument, and neatly wraps up the functionality, though. – Dave Newton Jan 15 '12 at 23:38

1 Answers1

0

There must be a better way, but if a is the result of the above:

a.flatten(1).collect { |arr| arr.size == 1 ? arr[0] : arr }

Also, I think the following is the equivalent of your combination creation (removes the inner map):

(1..6).map { |i| number.map { |d| d }.combination(i) }

Not 100% sure.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302