algorithm that will take numbers or words and find all possible combinations

algorithm, permutation, php

Solution

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

Problem

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? http://www.merriampark.com/comb.htm (dead link)

Original source