Shuffle Array
Posted on
16th Feb 2014 07:03 pm by
admin
Hi,
I am writing a script for a game that needs players to randomly be assigned a target (another player) in a loop so that each player is matched with someone other than who has them. See below:
Andy matched with Jan
Jan matched with Alex
Alex matched with Sue
Sue matched with Andy
My code retrieves name from the database in the order they sign up to play. I need to randomize the pairings for fairness.
Code: <?
$targets = array("Andy","Jan","Alex","Sue"); //names from DB in order of signup
?>
I make a copy of the array, shuffle it and check to make sure that two players are not paired with each other.
Code: <?
$targets = array("Andy","Jan","Alex","Sue"); //names from DB in order of signup
$targets_shuffled = $targets; //copy array
shuffle($targets_shuffled); //shuffle targets
?>
I am having trouble figuring out how to check for duplicate pairings and then reshuffling until it works. Originally I had looped through the arrays to check each pairing:
Code: <?
if($targets[$i] == $targets_shuffled[$i]){
echo "same!";
}
?>
Then I realized when one pair was matched incorrectly the whole pairing would need to be reshuffled. I tried to flag it, break out, and reshuffle, but could never get anything that worked.
Any ideas?
-Blake
Code currently:
Code: <?
shuffle($targets_shuffled);
echo "<br /><br />";
$retry = true;
$tries = 1;
while($retry == true){
echo "try: $tries<br />";
$retry = false;
$i = 0;
while($i < count($targets)){
if($targets[$i] == $targets_shuffled[$i]){
echo "found match!<br />";
$retry = true;
echo "breaking<br />";
break;
}
$i++;
}
$tries++;
}
?>
No comments posted yet
Your Answer:
Login to answer
199
43
Other forums
random generation
hi
i need help with generating this
numbers from 1-12
i want to generate in ran
Variable passed to each() is not an array or object
Hi,
This is a email a friend type of form, and it isn't working anymore.
<?
Spaghetti Code
So.
I've pretty much reached the point where I have so many isset s on one page that I can't
Backflush
I am looking for a report in SAP that would give me a list of all parts that are populated with a ba
Warning: session_start() [function.session-start]: Cann.....
hi, can someone help me with this? I keep getting this error....
Warning: session_start() [fu
batch file not building to webapps folder
Hello. I just started running Vista :P and can't seem to get my projects deployed. I found out how
Parse error: syntax error, unexpected T_ELSEIF in /home/......html/item.php on l
I do not know what is wrong with this. Hope some one can help. I do nto want to post the entire site
Agency Business Process
Hi,
I don’t understand the process of the agency business in SAP.
In my
gmdate() - want 1 hr before time
Hi,
I am using php gmdate().
Now I am entering all dates in my dbase using gmdate("Y-m-d
Am I setting up my sites oldschool?
Ok,
When I create a site I open a basic template that I have created that consists of a css f