SaRiD
Programmer
- Apr 19, 2003
- 45
A nice tricky one for you all.
I'm trying to figure out all the possible word combinations for a phrase.
E.g. "norman2 stuck on php"
I know the number of combinations as it is a factorial calculation (4 x 3 x 2 x 1)
What I need is to put that into a loop spitting out all the variations.
I've got this so far but it only works up to the total number of words and then goes wacky.
This works if there are 3 words, but 4 or more and it returns wrong after the number of words - run it to see what I mean.
Any thoughts, or answers?
I'm trying to figure out all the possible word combinations for a phrase.
E.g. "norman2 stuck on php"
I know the number of combinations as it is a factorial calculation (4 x 3 x 2 x 1)
What I need is to put that into a loop spitting out all the variations.
I've got this so far but it only works up to the total number of words and then goes wacky.
Code:
$kw = "norman2 stuck on php";
$arrKW = split(" ", $kw);
for($i = 0; $i < count($arrKW); $i++) {
$arrCount[] = $i;
}
$comb = factorial(count($arrKW));
$count = 0;
$swap = 1;
$orgn = 0;
for($a = 0; $a < $comb; $a++) {
for($i = 0; $i < count($arrKW); $i++) {
$arrCount[$i]++;
if($arrCount[$i] >= count($arrKW)) $arrCount[$i] = 0;
}
DisplayWords($arrKW, $arrCount);
$count++;
if($count >= count($arrKW)) {
$count = 0;
$org = $arrCount[$orgn];
$new = $arrCount[$swap];
$arrCount[0] = $new;
$arrCount[$swap] = $org;
$swap++;
echo "<br />";
}
}
function DisplayWords($arrKW, $arrCount) {
for($i = 0; $i < count($arrKW); $i++) {
echo $arrCount[$i] . " ";
#echo $arrKW[$arrCount[$i]] . " ";
}
echo "<br />";
}
This works if there are 3 words, but 4 or more and it returns wrong after the number of words - run it to see what I mean.
Any thoughts, or answers?