Jump to content

Finding All Possible Combinations of Array


pureDesi

Recommended Posts

I have an array, let's say it's values are ['A', 'B', 'C', 'D']. I want to list out all the possible combinations that can be achieved using these values so it would display something similar to

 

A

B

C

D

AB

BA

BC

BD

CA

CB

CD

DA

DB

DC

ABC

ABA

ABD

....

So on and so forth.

I've been working on it for some time and can't even come up with an algorithm, can anyone please assist me?

Thanks

It's not pretty, but it works.

<?php

function notLast() {

  global $tempArray, $values;

  $iterations = count($values);

  $testArray = array_reverse($tempArray);

  foreach ($testArray as $key => $value) {
    if ($value != ($iterations-1) ) {
      $testArray[$key]++;
      for ($i=$key-1; $i>=0; $i--) {
        $testArray[$i] = $testArray[$i+1] + 1;
      }
      $tempArray = array_reverse($testArray);

      return true;
    }
    $iterations--;
  }

  return false;

}

$values = array ( 'A', 'B', 'C', 'D');

$results = array();

for ($parts = 1; $parts<=count($values); $parts++) {

  $tempArray = array();

  for ($i=0; $i<$parts; $i++) {
    $tempArray[$i] = $i;
  }

  do {

    $value="";
    foreach ($tempArray as $index) {
      $value = $value . $values[$index];
    }
    $results[] = $value;

  } while (notLast());

}


echo "<pre>";
print_r($results);
echo "</pre>";

?>

Try this on for size.. it doesn't generate them in the order you expect though.

 

function make_list($array, $length) {
  return make_list_rec('', $array, $length);
}

function make_list_rec($prefix, $array, $length) {
  $ret = array();
  $append = array();

  foreach ($array as $a) {
    $ret[] = "$prefix$a\n";
    if ($length === 1) continue;

    # Recurse
    $new_length = $length - 1;
    $new_prefix = $prefix . $a;
    $append = array_merge($append, make_list_rec($new_prefix, $array, $new_length));
  }

  return array_merge($ret, $append);
}

$array = array('a', 'b', 'c');
var_dump(make_list($array, 3));

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.