views:

47

answers:

3

Hi there,

My head gets stucked finding an algorithm for my problem.

Assume I have N Numbers (lets say 4) and I want have ALL X-Partitions (X = N/2)

Example:

2-Partitions of {1,2,3,4} are: (1,2) (1,3) (1,4) (2,3) (2,4) (3,4) [Simply: all combinations]

I don't have a clue how to generate these combinations. If someone of you have an idea in Mind (I don't care what language. Pseudocode ist totally enough. I don't care if it's iterative or explicit).

Best regards, Bigbohne

A: 
foreach i in SET
    foreach j in SET
        if i < j, SAY "I have a partition ($i,$j)"
    NEXT j
NEXT i

this depends on an iterating feature for your set, and operates in N^2 time.

For Matlab, check out the functions provided for you, e.g. combnk

maxwellb
fwiw, these are, as you say "combinations", a PARTITION is a different definition when referring to sets: a partition of a SET {1,2,3,4} is a distinct way of putting the elements of the SET into different containers (subsets). So, { {1,2}, {3}, {4} }, is a partitioning of {1,2,3,4}.
maxwellb
this will generate duplicates
second
Fine...BUT !!!! what if 'X' gets larger than 2 ? ... lets say ... i have {1,2,3,4,5,6,7,8} and I want to have all 4-Combinations? like: {1,2,3,4}, {1,2,3,5} ...
Bigbohne
@second: thanks. @Bigbohne: then you would have more levels of loop. @tauran: indeed, it is slow, but a start. using the nchoosek function provided by Matlab is indeed a better solution.
maxwellb
+5  A: 

Matlab has a function for this:

http://www.mathworks.com/help/techdoc/ref/nchoosek.html

>> x = [1,2,3,4]

x =

1     2     3     4

>> nchoosek(x, 2)

ans =

 1     2
 1     3
 1     4
 2     3
 2     4
 3     4

Loop constructs like maxwellb's are awfully slow in matlab...

tauran
THX!That's what i've searched for!
Bigbohne
+1  A: 

Here's matlab code,

myNums = [2,3,6,5];
for i = 1:size(myNums,2)
    combinationsSet{i} = nchoosek(myNums,i);
end
reddy
the loop is for changing the number of elements to choose,
reddy