Page 1 of 1

All Possible Combinations code

Posted: Sat Nov 11, 2006 4:55 pm
by boonika
Hi,

I would like to get all the possible combinantions from a pool of teams. For example; there are 3 teams (Chelsea, Arsenal and Man U). I would like to have a script that automatically gives me: Chelsea - Arsenal, Chelsea - Man U, Arsenal - Man U. This is a combination of 2 out of 3. I would like to have code for combinations of 2 out of X (variable number of teams).

Info on combinatorics: http://en.wikipedia.org/wiki/Combinatorics

Does anyone have an idea about how I should script this into PHP?

Thans :)

Posted: Sat Nov 11, 2006 5:01 pm
by feyd
There's been a thread on this fairly recently..

viewtopic.php?t=55043

Posted: Sat Nov 11, 2006 5:01 pm
by aaronhall
Load the teams into an array. Something like:

Code: Select all

for($i=0; $i<count($teamsArray); $i++) {
	
	for($j=$i+1; $j<count($teamsArray); $j++) {
		echo $team[$i], " - ", $team[$j];
	}
	
}

Posted: Sat Nov 11, 2006 8:05 pm
by Cameri
aaronhall wrote:Load the teams into an array. Something like:

Code: Select all

for($i=0; $i<count($teamsArray); $i++) {
	
	for($j=$i+1; $j<count($teamsArray); $j++) {
		echo $team[$i], " - ", $team[$j];
	}
	
}
:D

Code: Select all

$total_teams = count($teamsArray);
// count() inside the for loop will do this:
// call count($teamsArray) as many elements the array has +1 one, and this squared, plus one again
// so it's better outside
for($i=0; $i<$total_teams; $i++) {
	for($j=$i+1; $j<$total_teams; $j++) {
		echo $teamsArray[$i], " - ", $teamsArray[$j];
	}
}

Posted: Sun Nov 12, 2006 2:46 am
by boonika
Thanks a lot guys, you rule! :lol: