php - Matching an array of people for gift giving, how to handle this edge case -
i'm matching array of people each other. can't matched , each person can matched 1 other. have worked out run edge case. if person being matched person has not yet been matched against, stuck.
example:
$names = array('dad','mom','harrald','yu','sandra','dave', 'andy & kim'); $drawn = array(); $tn = count($names)-1; $i = mt_rand(0, $tn); foreach ($names $name) { while($name == $names[$i] || in_array($names[$i], $drawn)) { $i = mt_rand(0, $tn); } echo $name. ' has ' . $names[$i].'<br />'; array_push($drawn, $names[$i]); }
this produce:
dad has sandra
mom has yu
harrald has dave
... etc, etc.
the problem when gets last element in array, 'andy & kim', if 'andy & kim' element not yet added $drawn
array have edge case because can't match 'andy & kim' themselves. in example can result in getting trapped in while loop , timing out... see mean? how handle (this solely own amusement went knock out quick gift giving match-up script mom use , realized potential problem).
oh, better ways implement such pattern interesting see. thx!
surely, rather using iteration, it's easier shuffle array; , match 1st 2nd, 2nd 3rd, etc, last being matched 1st again complete circle
Comments
Post a Comment