Gossamer Forum
Home : General : Perl Programming :

random teams

Quote Reply
random teams
Trying to set up a script that creates random teams of a certain number of players.

I have the players in an array. Lets say there are 6 players.
Now, I want to be able to spread these into different teams, which I set in a box(the number of teams).

<select size="1" name="teams">

I display this from on a page, and press a button to go to the script file.
Where I have something like this. I pick out the players from a file and check who of them are playing that type of game.
Then I try to give them a random team. The problem is that all of the players end up on the same team. No matter how many teams I want to set up. The team they are set to is different from each time, but all end up on same team.

And I don't know if there is any way of getting the teams to be fair? It will always be the right number of players (2-4-6-8 and so on), but how can I place like 2 players on that team, and two on another?

This is the code I have:

open (FILE, "$file") or feilmelding("couldnt open $file: $! \n");
my@players = <FILE>;
close (FILE);
my $number = 0;
foreach $player (@players){
($number1,$name,$games,$date) = split(/\|/, $player);
if ($games =~ /warcraft3/i) {

if ($FORM{'teams'} != "") {
srand (time|$$);
$numberofteams = $FORM{'teams'} + 1;
$yourteam = int(rand($numberofteams));
print "<tr><td><input type=\"text\" readonly=\"readonly\" size=\"25\" value=\"$name\" name=\"$name\"/> <input type=\"text\" readonly=\"readonly\" size=\"2\" name=\"$number\" value=\"$yourteam\" />$number</td></tr>";
I miss a lot of code yet. Anyone who can help?


- kbergem
Quote Reply
Re: [perlman] random teams In reply to
I will try to explain it a little better so people understand easier.

I have manage to get random numbers now on each of the players. Found a piece of code that helped me, but now my problem appears.
How can I get the teams to be even?

Say I have 10 players.
I do the random test, and 7 of them get number 1, and the 3 others get number 2.(7=1 3=2)
How can I do a check before I print my results?
If I get the numbers above, how can I check them before I print it, so that it has to be 5 players on each team?

$min_number = 1;
$numberofteams = $FORM{'teams'} + 1;
$random_number=rand($numberofteams - $min_number);
$random_number += $min_number;
$random_number = int ($random_number);

The $FORM{'team'} is set by a user which choose the number of teams between 1-6.


1. Name 2
2. Name 2
3. Name 2
4. Name 1
5. Name 2
6. Name 1
7. Name 2
8. Name 2
9. Name 1
10. Name 2

This is an example of how the print can be displayed.
If I run the script over and over again, I will eventually find a match(even teams), but this can take a while.

Does anyone have a clue how I can check for this?
Thanks a lot of any help!