1

样本数组:

$player = array("lawrence","joey","jason","joel","bianca","paulo","albert");

我想将一个数组与其自身匹配,以便它从自身获取一个值而不会得到一个重复的值:

"lawrence" => "lawrence"; //must not contain itself
"joey" => "lawrence"; //must not assign value already assigned to that value

简而言之:它就像一个 交换礼物算法

4

2 回答 2

2
$player = array("lawrence","joey","jason","joel","bianca","paulo","albert");
shuffle($player);
$player2 = $player;
array_unshift($player2, array_pop($player2));

$combined = array_combine($player, $player2);

随机播放,将其转置 1 以创建有保证的唯一匹配,重新组合。

于 2013-11-04T08:02:38.617 回答
0

我找到了这篇文章:使用 PHP,随机配对一组项目,不与自身配对,不直接配对

最佳答案看起来非常好:https ://stackoverflow.com/a/3758775/623952

// result array
$res = array();
// get first element and save it
$first = $ele1 = array_shift($arr);
while(count($arr)) {
    // get random element
    $ele2 = array_rand($arr);
    // associate elements
    $res[$ele1] = $arr[$ele2];
    // random element becomes next element
    $ele1 = $arr[$ele2];
    // delete the random element
    array_splice($arr, $ele2, 1);
}
// associate last element woth the first one
$res[$ele1] = $first;

这给了我:

Array
(
    [lawrence] => joel
    [joel] => joey
    [joey] => jason
    [jason] => paulo
    [paulo] => albert
    [albert] => bianca
    [bianca] => lawrence
)

您可能需要在那里检查以查看您的礼物交换中是否“该人选择了自己”。

于 2013-11-04T08:01:36.877 回答