I've got 10 players that should play with different opponent each week. Not everyone is coming each week so I have from 4 to 10 players and have to shuffle opponent for each one present.
I use html checkbox to select players
<input type='checkbox' name='checkboxvar[]' value='01'>01<br>
<input type='checkbox' name='checkboxvar[]' value='02'>02<br>
<input type='checkbox' name='checkboxvar[]' value='03'>03<br>
<input type='checkbox' name='checkboxvar[]' value='04'>04<br>
<input type='checkbox' name='checkboxvar[]' value='05'>05<br>
<input type='checkbox' name='checkboxvar[]' value='06'>06<br>
<input type='checkbox' name='checkboxvar[]' value='07'>07<br>
<input type='checkbox' name='checkboxvar[]' value='08'>08<br>
<input type='checkbox' name='checkboxvar[]' value='09'>09<br>
<input type='checkbox' name='checkboxvar[]' value='10'>10<br>
I want to log who was playing with who so I keep array of each player in a single file; to match I exclude selected player from matching array, diff with array of previous opponents and then rand the one
$players = $_POST['checkboxvar'];
$opponents = $_POST['checkboxvar'];
shuffle($opponents);
foreach($players as $value)
{
$playerarray = json_decode(file_get_contents($value.'.json'), true);
$matching = array_diff($opponents,$playerarray);
foreach (array_keys($matching, $value, true) as $key) {unset($matching[$key]);}
$result = array_rand(array_flip($matching), 1);
echo $value.' is playing against ';
echo $result;
$playerarray[] = $result;
foreach (array_keys($opponents, $result, true) as $key) {unset($opponents[$key]);}
file_put_contents($value.'.json',json_encode($playerarray));
};
Problem with my code is that matching array is shrinking every iteration so often it goes empty after diff with array from file so execution stops and I have no opponent for this and each next player. I know there has to be some way to loop the code until if finds the right combination where everybody has it's own opponent.
Any suggestions how to determine the right pattern and then update array of every single player ?
Aucun commentaire:
Enregistrer un commentaire