All Possible Combinations code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
boonika
Forum Newbie
Posts: 18
Joined: Tue May 24, 2005 1:46 pm

All Possible Combinations code

Post 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 :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

There's been a thread on this fairly recently..

viewtopic.php?t=55043
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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];
	}
	
}
User avatar
Cameri
Forum Commoner
Posts: 87
Joined: Tue Apr 12, 2005 4:12 pm
Location: Santo Domingo, Dominican Republic

Post 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];
	}
}
boonika
Forum Newbie
Posts: 18
Joined: Tue May 24, 2005 1:46 pm

Post by boonika »

Thanks a lot guys, you rule! :lol:
Post Reply