Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 339
JasonDavis Avatar asked Aug 10 '09 17:08

JasonDavis


People also ask

How do you find all the possible combinations of numbers?

To calculate combinations, we will use the formula nCr = n! / r! * (n - r)!, where n represents the total number of items, and r represents the number of items being chosen at a time. To calculate a combination, you will need to calculate a factorial.

How do you calculate algorithm combinations?

Traditional formula of r-combination (or n choose r) is: C(n, r) = n! / (r! . (n-r)!)

How do you generate all possible combinations of one list?

Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!

What are all the possible combinations of 1234?

1234, 1243, 1423, 4123, 1324, 1342, 1432, 4132, 3124, 3142, 3412, 4312, 2134, 2143, 2413, 4213, 2314, 2341, 2431, 4231, 3214, 3241, 3421, 4321.


1 Answers

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
like image 164
VolkerK Avatar answered Sep 23 '22 13:09

VolkerK