I’m trying to make a draw for a secret Santa.
I collect in a table the information of the person and the name of the person on whom it should not fall (to avoid couples).
However during my PHP loop I can’t take into account my exclusions
foreach ($supplier as $sup){
$exclude = $sup['blacklist'];
$data = $recipient;
$temp = array_diff($data[], array($exclude));
echo $temp[rand(0, sizeOf($temp))];
foreach ($recipient as $key=>$recip){
if ($sup['surname'] !== $recip['surname']){
$result[] = ['recipient' => $recip, 'supplier' => $sup];
unset($recipient[$key]);
}
}
}
How can I take into account this blacklist please?
2
Answers
this is my code with shuffle
Your solution is fine, but with that nested loop it’s going to start behaving poorly as the list of participants grows. You can accomplish the task with a single array and two linear passes over it:
Output:
There is a caveat to this approach, though. It will only work with strict 1:1 blacklist arrangements. Once there is a love triangle [or quardrangle or above] or any polyamory, neither of our solutions is equipped for these extra dimensions.