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
BSP Ext - tableView - Sort - NEWBIE
Hi,
I have been trying to get the sort to work. I have defined the column definitions by fillin
Transferring session variables into MySQL
I am trying to transfer $_SESSION variables into MySQL. However there is an error in my MySQL statem
Protecting forms
Alright, I want to protect some forms of mine from SQL Injections, because I had someone earlier spa
MySQL issue
I am taking sentences through a form on page. Then checking some condition and trying to insert them
php code generators
All
Whilst enjoying learning a new language i have come accross a number of free code generat
add 20 000 to the rowcnt
Hi ...
I need to add 20 000 to the row count but just cant find a way to do this i am new to php
Looking for help reading a .txt or .ini file and outputting the info.
I have a file called Info.ini and It has the following info:
Code: [General]
Online=0
I wou
I think i'm using the syntax incorrectly
Hi Everyone!
I'm new to this forum and a newbie with PHP - I'm glad I found this site - I hop
writing a screen scraper
Hello,
I'm writing a screen scraper application and want to be able to get absolute addresses
Simple PHP/Java Help..
Hi,
I'm trying to build a little program to do with calculating postage. Unfortunately i haven't