[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Combinatorics and permutations? Help?

David Palm

3/11/2008 11:06:00 AM

Hi,
I have a problem involving combinatorics and permutations and my brain hurts.

The problem: I have a hash of products in input. I then build an array of equivalent products for each input product. I end up with an array such as this:
{
:input_prod_1 => [:p1_1, :p1_2, ... , p1_x],
:input_prod_2 => [:p2_1, :p2_1, ..., p2_y],
...
:input_prod_m => [:pm_1, :pm_1, ..., pm_z]
}

I need all the unique combinations of each product from the first group with each of the second. For example:
given: [ [:p1, :p2], [:p3, p4] ]
I need to obtain: [ [:p1, :p3], [:p1, :p4], [:p2, :p3], [:p2, :p4] ]

Given: [ [:p1], [:p2, :p3, :p4] ]
I need: [ [:p1, :p2], [:p1, :p3], [:p1, :p4] ]

The number of input products is in the order of tens (max); the same goes for the number of equivalent products. This means the total number of partitions is pretty large and I need to weed out the equivalent ones soon/fast enough to reduce the total number.

I've been making attempts with the permutation gem all morning; looks like it's doing the "right thing", but frankly my maths skills are lacking and I can't really figure out how to use it (should I?).

Also: order is not important for the result arrays.

This is easy, right? :-/

3 Answers

Emmanuel Oga

3/11/2008 11:23:00 AM

0

William James

3/11/2008 11:38:00 AM

0

On Mar 11, 5:06 am, David Palm <dvd...@gmail.com> wrote:

> I need all the unique combinations of each product from the first group with each of the second. For example:
> given: [ [:p1, :p2], [:p3, p4] ]
> I need to obtain: [ [:p1, :p3], [:p1, :p4], [:p2, :p3], [:p2, :p4] ]
>
> Given: [ [:p1], [:p2, :p3, :p4] ]
> I need: [ [:p1, :p2], [:p1, :p3], [:p1, :p4] ]

p [[1,2],[3,4]].inject([[]]){|old,lst|
lst.inject([]){|new,e| new + old.map{|c| c.dup << e}}}

David Palm

3/11/2008 12:12:00 PM

0

On Tue, 11 Mar 2008 20:40:11 +0900, William James wrote:
> p [[1,2],[3,4]].inject([[]]){|old,lst|
> lst.inject([]){|new,e| new + old.map{|c| c.dup << e}}}

awesome. Totally rocks.