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.