【问题标题】:PHP match an array into itself randomatically [duplicate]PHP将数组随机匹配到自身[重复]
【发布时间】:2013-11-14 19:54:35
【问题描述】:

样本数组:

$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

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

【问题讨论】:

  • i want to match an array to itself so that it gets a value from itself without getting a duplicated value: 你能用英语说这个吗?
  • 你想......从你的数组中随机选择值,而不是让它重复它选择的值吗?
  • 是的,很准确@gloomy.penguin,此外,无法再次选择所选值
  • 我在想目标就像一个 OUTER JOIN,玩家应该配对...除了这两个示例之外,您能否举一个 起作用的示例那不?和@HankyPanky - 给 OP 打分以选出本周最好的新英语单词。随机是我一段时间以来见过的最酷的东西。
  • 交换礼物算法——你的意思是像一个秘密的圣诞老人?

标签: php arrays algorithm list


【解决方案1】:

我发现了这个帖子:Using PHP, randomly pair up group of items, not pairing any with itself, no direct pairings

而且上面的答案看起来很不错: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
)

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

【讨论】:

  • @gloomy.penguin 谢谢,你最近回答的那个也在工作
  • @LawrenceBoadilla 我看到其他人已经为您的问题提供了解决方案(绿色复选标记),但您似乎仍在讨论 cmets 中的问题...有什么我可以添加到此代码中的吗整体解决您的问题?
  • @实际上 deceze 的算法已经可以正常工作了,我只是一开始就没有得到它。我认为它使用 rot13 有点像算法。
【解决方案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 以创建有保证的唯一匹配,重新组合。

【讨论】:

  • 这是我心目中的外连接想法吗? (每个数组成员限制一个?)
  • 我不认为这是同一个想法。这只是将数组旋转一个位置并重新组合它。
  • 它很好但是它有一个图案,必须在上面添加随机效果
  • 那么像一个秘密的圣诞老人?
  • @Lawrence 唯一的模式是 a > b, b > c 的数组中有一个顺序,abbc。在组合后再次洗牌以移除该链。
猜你喜欢
  • 2018-12-17
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2011-05-21
相关资源
最近更新 更多