Note that there are some explanatory texts on larger screens.

plurals
  1. POOne-liner Algorithm to Combine Arrays into Arrays of All Possible Value Combinations?
    text
    copied!<p>Not quite sure I have the question fully formed, but what I'm trying to do is basically this:</p> <pre><code># where the indices correspond to attributes fore example: # [type, status] x = %w(a b) y = %w(c d) combine(x, y) #=&gt; [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]] </code></pre> <p>The order of the array is always the same, so the reverse of each, such as <code>[b, a]</code>, are not included in the result.</p> <p>What is this called and what's an efficient way to implement this?</p> <p>I see <a href="http://www.ruby-doc.org/core/classes/Array.html#M000288" rel="nofollow">Array#permutation</a>, but that's not quite it...</p> <p>This would hopefully work for any number of arrays and values: <code>combine(*arrays)</code></p> <p>Thanks!</p> <p><strong>Update</strong></p> <p>Here's a better example of what I'm looking for:</p> <p>This <code>(x | y).combination(x.length).to_a</code> produces the following:</p> <pre><code>x = ["front_door", "open"] y = ["back_door", "closed"] (x | y).combination(x.length).to_a =&gt; [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]] </code></pre> <p>The actual result I'm looking for is this:</p> <pre><code>=&gt; [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]] </code></pre> <p>Or if it were a longer array:</p> <pre><code>x = ["house", "front_door", "open"] y = ["building", "back_door", "closed"] compute(x, y) =&gt; ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"] </code></pre> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload