How can I create a random, circular partner assignment?
I'm allowing users to register on my site for a 'game'; as is normal, they all receive unique IDs. At a given point in time, registration will cease. At that time, I would like to run code to assign partners, but not pairs.
So, if I had the following:
+--------+-------+
| user_id | partner | +--------+-------+ |
1 |
| |
3 |
| |
7 |
| |
11 |
| |
12 |
| |
18 |
| +--------+-------+
what would I do to end up with something like this:
+--------+--------+
| user_id | partnr | +--------+--------+ |
1 |
7 | |
3 |
12 | |
7 |
18 | |
11 |
1 | |
12 |
11 | |
18 |
3 | +--------+--------+
1,7,18,3,12,11;1,7,18,3,12,11
$query = "SELECT users FROM tabl";
$result = mysql_query ($query)
or die ("Query '$query' failed with error message: \"" . mysql_error () . '"');
while ($row = mysql_fetch_array($result)) {
$users[] = $row[0];
}
$current = end($users);
$partners = array();
foreach ($users as $user)
{
$partners[$user] = $current;
$current = $user;
}
print_r($partners);
This seems to work, thanks to Sjoerd, but I开发者_开发百科 need to write it back to the partner column.
- Retrieve the list of users.
- Shuffle this list (optional).
- Assign each user the next one in the list as partner, where the last user gets the first user as partner.
Code to loop through the array and assign partners:
$users = array('john', 'jack', 'jones', 'joelle', 'jesica');
$current = end($users);
$partners = array();
foreach ($users as $user)
{
$partners[$user] = $current;
$current = $user;
}
print_r($partners);
- Select out the ids in a random order
- Have two copies of the resulting array
- Pop one element of the end of one array and push it on the top (ie offset the entire array by one)
Update the table as user_id,partner_id pairs
$results = mysql_query("SELECT user_ids FROM -tablename- ORDER BY RAND()"); $user_ids = array(); $partner_ids = array(); while($row = mysql_fetch_array($results)) { $user_ids[] = $row['user_id']; $partner_ids[] = $rowp['user_id']; } $lastPartnerId = array_pop($partner_ids); array_unshift($partner_ids,$lastPartnerId); for($i=0;$i<count($user_ids);$i++) { mysql_query("UPDATE -tablename- SET partner_id = {$partner_ids[$i]} WHERE user_id = {$user_ids[$i]}"); }
Sorry if there are mistakes ... I havn't been coding PHP for a long time ...
$i = rand(1, length($players) - 1)
for ($p = 0; $p < length($players); $p++)
{
$partners[$p] = $players[$i];
if (++$i > length($players))
{
$i = 0;
}
}
精彩评论