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
Need help with a mail notify function
I was tasked with setting up a site that's been prewritten. The site is basically a form that captur
foreach iterator
Hi Guys
Does the foreach loop have an inbuilt iterator ?
Help with PHP Email Script
Hi guys,
I'm a newbie to php and need help with the script below:
At the moment when I
Calender Not Opening
The following code is not loading the javascript calender in another window. It's not doing anything
Best way to read this text file.
Hi.I am planning to make a small application in C# to convert the players from Football manager 2010
foreach help.
Hello all,
First time I'm attempting to use a foreach statement and was just wondering if my
Install page
How do I make it so when a user submits information on the Install page, it'll right it into the cor
small inaccuracies
I have this code to convert fractional base 10 into base 2:
while($num > 0)
Batch update record with Pagination
Hoping someone can help me with this issue I'm having, im trying to batch update records from a resu
Need help with some php code :)
Hey! I'm quite new to this whole thing, so please don't fire me with shait on this one =D
I'm