All possible combinations algorithm

Dan Wilson dan at acucore.com
Wed Jun 15 09:35:57 MDT 2005


On Wed, 2005-06-15 at 08:45 -0600, Josh Coates wrote:
> >Given an array of elements (with an unknown length), I need to find all
> >possible combinations of that array.
> 
> um...dude - this is kind of a silly question.
> 
> is this one of your homework problems..?

Wow... leave it Josh to bring someone else down in order to make himself
look that much more intelligent.  That was pretty jerk.

I already had a solution... but I felt it was bruit-force. I was wanting
a more optimized solution/algorithm... and was having a brain-fart.
Sorry I didn't indicate that.

Here's the code I currently have:

function combos($data) {
 $result[] = implode(' ', $data);
 foreach ($data as $item) {
  $match = "$item ";
   foreach ($data as $other_item) {
    $match .= $other_item != $item ? "$other_item " : '';
   }
  $result[] = trim($match);
 }
 return $result;
}

Does anyone have anything cleaner or more optimized?

-Dan




More information about the PLUG mailing list