3

I have an array of 10 numbers. I would like all combinations of three numbers out of the available 10. However, the order is not relevant. That is I do not want combinations of the same numbers in a different order (after 1,2,3 is generated 2,3,1 should not appear). Also, numbers should not be repeated within the combination (i.e. no 1,1,1). I know how to create the table with foreach, yet I'm stuck on how to generate the possible combinations. Thanks for your help!

Duncan
  • 31
  • 1
  • Can you show us some examples of combinations? – Rohit Choudhary Mar 06 '13 at 11:43
  • 1,2,3 1,4,3 1,5,3 1,6,3 1,7,3 etc – Duncan Mar 06 '13 at 11:44
  • Your question is not a good question. Your question does not show any effort to find an answer, what you have tried, or what you are trying to achieve (apart from doing your homework, my guess). Have a look at the suggested possible duplicates which I'm certain deal with your exact problem. If not, please explain why. – ExternalUse Mar 06 '13 at 11:51
  • Thank you for your quick help, I found a solution here: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n in particular the comment of Akseli Palén, who refers to https://gist.github.com/doph/3118596 – Duncan Mar 06 '13 at 12:02

3 Answers3

0

A good approach is to use array_unique() to remove duplicates from your array. Then, each time you use an element you should pop it using array_pop() so that it won't be used again.

deadlock
  • 8,894
  • 8
  • 44
  • 67
0

Numbers cannot be repeated, then does that mean 1,2,1 is also not allowed? If so, as a first step remove all duplicate numbers in the given set, as deadlock suggests. Then use an algorithm to find combinations. Many such algorithms are covered in the 'duplicate of' questions suggested by other users.

Amit
  • 1,775
  • 12
  • 20
0

Borrowing from user187291's answer here, with a few modifications to suit your needs, the following should be what you want:

$a = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

$len  = count($a);
$list = array();

for($i = 1; $i < (1 << $len); $i++) {
    $c = '';
    for($j = 0; $j < $len; $j++)
        if($i & (1 << $j))
            $c .= ',' . $a[$j];
    $list[] = ltrim($c, ',');
}

$answer = array();

foreach ($list as $comb)
{

  if (3 == count(explode(',', $comb)))
  {
    $answer[] = $comb;
  }

}

echo '<pre>' . print_r($answer, true);
Community
  • 1
  • 1
MichaelRushton
  • 10,294
  • 3
  • 38
  • 59