
本文旨在解决在使用 PHP 实现 Secret Santa 脚本时,当用户数量为奇数时出现的重复配对问题。通过分析问题代码,找出导致重复配对的原因,并提供修复后的代码示例,同时提供一种更优雅的循环配对方案,确保所有用户都能参与到 Secret Santa 活动中。
在实现 Secret Santa 脚本时,一个常见的挑战是如何处理奇数数量的用户。原始代码在处理奇数用户时,会出现某个用户被分配到“No Pair”两次的情况。这是由于递归调用 generateUsers 函数时,在用户数量变为 1 之后,仍然会执行判断逻辑导致的。
以下是修复后的代码:
class Match
{
protected $startingUsers = [
"User1",
"User2",
"User3",
"User4",
"User5",
];
protected $pairs = [];
protected $matchedUsers = 0;
function getPairs(): array
{
if ($this->generateUsers($this->startingUsers)) {
return $this->pairs;
}
return [];
}
function generateUsers(array $defaultUsers, array $updatedUsers = []): bool
{
$users = (!empty($updatedUsers)) ? $updatedUsers : $defaultUsers;
if (count($users) > 1) {
if ($this->matchedUsers !== count($this->startingUsers)) {
// Pick random user and match with current user. Reset array and repeat until 1 or no users left.
$randomUserIndex = rand(1, count($users) - 1);
$this->pairs[] = [$users[0], $users[$randomUserIndex]];
unset($users[$randomUserIndex]);
unset($users[0]);
// Remove pair from list so they can't be assigned again. Reset array for 0 based index $users[0]
$newUsers = array_values($users);
// Check that there are two or more users
if(count($newUsers) > 1){
$this->generateUsers($this->startingUsers, $newUsers);
}
$this->matchedUsers += 2;
}
}
// If only one user remains can't allocate a Pair
if (count($users) === 1) {
$orderedUsers = array_values($users);
$this->pairs[] = [$orderedUsers[0], "No Pair"];
return true;
}
return true;
}
}
$match = new Match();
foreach ($match->getPairs() as $pair) {
echo "$pair[0] gets $pair[1]";
echo "\n";
}关键的修改在于在递归调用 generateUsers 之前,增加了一个条件判断 if(count($newUsers) > 1)。 只有当剩余用户数量大于 1 时,才进行递归调用,避免了重复配对的问题。
立即学习“PHP免费学习笔记(深入)”;
更优雅的循环配对方案
除了修复原始代码中的问题,还可以考虑一种更优雅的循环配对方案,确保每个用户都有一个配对对象,避免出现“No Pair”的情况。 这种方案的核心思想是创建一个用户链,每个用户都将礼物送给链中的下一个用户,最后一个用户则将礼物送给链中的第一个用户。
以下是实现循环配对方案的示例代码:
class Match
{
protected $startingUsers = [
"User1",
"User2",
"User3",
"User4",
"User5",
];
protected $pairs = [];
function getPairs(): array
{
$users = $this->startingUsers;
shuffle($users); // 打乱用户顺序,确保随机性
for ($i = 0; $i < count($users); $i++) {
$giver = $users[$i];
$receiver = $users[($i + 1) % count($users)]; // 使用取模运算实现循环
$this->pairs[] = [$giver, $receiver];
}
return $this->pairs;
}
}
$match = new Match();
foreach ($match->getPairs() as $pair) {
echo "$pair[0] gets $pair[1]";
echo "\n";
}在这个方案中,shuffle($users) 函数用于打乱用户顺序,$receiver = $users[($i + 1) % count($users)] 使用取模运算 % 来确保最后一个用户能够正确地配对到第一个用户,形成一个循环。
总结
处理 Secret Santa 脚本中的奇数用户配对问题,可以采用修复递归调用逻辑的方式,也可以采用更优雅的循环配对方案。 循环配对方案避免了“No Pair”的情况,确保所有用户都能参与到 Secret Santa 活动中,并且代码逻辑更加简洁明了。 在实际应用中,可以根据具体需求选择合适的方案。
以上就是PHP Secret Santa 奇数用户配对问题解决方案的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号