2

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

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
Bigbohne
  • 1,356
  • 3
  • 12
  • 24

3 Answers3

5

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
  • 7,986
  • 6
  • 41
  • 48
1

Here's matlab code,

myNums = [2,3,6,5];
for i = 1:size(myNums,2)
    combinationsSet{i} = nchoosek(myNums,i);
end
Chenna V
  • 10,185
  • 11
  • 77
  • 104
0
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
  • 13,366
  • 2
  • 25
  • 35
  • 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 Sep 07 '10 at 15:45
  • this will generate duplicates – second Sep 07 '10 at 15:45
  • 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 Sep 07 '10 at 15:47
  • @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 Sep 07 '10 at 19:36