-5

I have an array with the following values

$in = array("A","B","C","D","E");

I want to get all possible combinations by a specified (n) no.

e.g if n = 2 , return AB, AC, AD, AE, BC, BD, BE, CD, CE, DE

IF n = 3, return ABC, ABD, ABE, BCD, BCE, CDE

Please, how can I achieve this in PHP?

Rahul
  • 18,271
  • 7
  • 41
  • 60
user297056
  • 23
  • 8
  • 1
    Can you show what you have tried and achieved? Also why is Javascript and jQuery tagged? – Rajesh Jan 18 '16 at 13:31
  • 2
    There are plenty of solutions to this particular homework assignment if you research using Google. – Rory McCrossan Jan 18 '16 at 13:32
  • 1
    Check this answer http://stackoverflow.com/questions/19067556/php-algorithm-to-generate-all-combinations-of-a-specific-size-from-a-single-set – DanieleO Jan 18 '16 at 13:40

1 Answers1

0
function sampling($chars, $size, $combinations = array()) {

  # if it's the first iteration, the first set 
  # of combinations is the same as the set of characters
  if (empty($combinations)) {
    $combinations = $chars;
  }

  # we're done if we're at size 1
  if ($size == 1) {
    return $combinations;
  }

  # initialise array to put new values in
  $new_combinations = array();

  # loop through existing combinations and character set to create strings
  foreach ($combinations as $combination) {
    foreach ($chars as $char) {
      $new_combinations[] = $combination . $char;
    }
  }

  # call same function again for the next iteration
  return sampling($chars, $size - 1, $new_combinations);

}

// example
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);

More about it here

Community
  • 1
  • 1
Mihail Petkov
  • 1,535
  • 11
  • 11