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:
Did you know?Explore Trending and Topic pages for more stories like this.
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
Populate drop down list from table??
Lets say for arguments sake that i have a table which contains the numbers 1 to 10.
How can i get
TinyMCE / Ajax Postback Problem
Hiya all,
I have a page which loads the TinyMCE editor. On the postback I obviously want to f
Simple Question
I know this is a simple question, that if I knew what it was technically called i could probably loo
single values into sql field
i have a form which i want the user to able to select multiple answers. But i want the answers to be
Default TimeZone
The server I'm working with is hosted in America so all times inserted into the database are coming
Recode Abap Dynpro into Web Dynpro
Hi All,
A client has asked us to look at rearchitecting a custom transaction that was developed
present value of sequence?
Hi
Please help me to find out the present value of sequence?
Thanks
phpMailer not working ..........
HI,
I was playing with the phpMailer script and tried to send a smiple mail using their test scri
DELETE rows based on content
I have a link in my rows
$bit="http://bit.ly/abcd";
$query = mysql_query("D
Why use OOP?
Can someone explain to me why I should use OOP instead of procedure based code.
Im building a