views:

535

answers:

1

I am looking for an algorithm that will take numbers or words and find all possible variations of them together and also let me define how many values to look for together.

Example lets say the string or array is:
cat
dog
fish

then the results for a value of 2 could be:
cat dog
cat fish
dog cat
dog fish
fish cat
fish dog

SO the results from the set of 3 items are 6 possible variations of it at 2 results matching
with 3 results matching it would be:

cat dog fish
cat fish dog
dog cat fish
dog fish cat
fish cat dog
fish dog cat
...probably more options even

I have found a link on Stackoverflow to this example that does this but it is in javascript, I am wondering if anyone knows how to do this in PHP maybe there is something already built?

javascript version here

+11  A: 

Take a look at http://pear.php.net/package/Math_Combinatorics

<?php
require_once 'Math/Combinatorics.php';
$words = array('cat', 'dog', 'fish');
$combinatorics = new Math_Combinatorics;
foreach($combinatorics->permutations($words, 2) as $p) {
  echo join(' ', $p), "\n"; 
}

prints

cat dog
dog cat
cat fish
fish cat
dog fish
fish dog
VolkerK
Very nice PEAR package, I'll use it in the future.
Alix Axel
That is awsome thanks for the info, do you have any idea what the difference between these 2 is $combinations and $permutations in the example script?
jasondavis
In permutations the order of the elements counts, in combinations the order is irrelevant. E.g. (cat,dog) and (dog,cat) both are included in the result of permutations() while the result of combinations() will only include one of them, the second is considered equal.
VolkerK