使用PHP,随机配对组项目,没有任何配对与自己没有直接配对 [英] Using PHP, randomly pair up group of items, not pairing any with itself, no direct pairings

查看:218
本文介绍了使用PHP,随机配对组项目,没有任何配对与自己没有直接配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一组项目的数组。

Assume you have a set of items in an array.

A,B,C,D,E,F,G,H

A, B, C, D, E, F, G, H

使用PHP,你会怎么随机配对的字母在一起,没有用自己的副本配对呢?

Using PHP, how would you randomly pair the letters together without pairing them with a duplicate of themselves?

这样的代码:

 A->pairedLetter = G
 B->pairedLetter = C
 C->pairedLetter = E
 D->pairedLetter = A
 E->pairedLetter = B
 F->pairedLetter = D
 G->pairedLetter = F

等等...

and so on...

编辑: 哦,还有,如果是搭配F,F不能与A.配对 因此将必须尽可能多的关系,因为有项目

Oh, and also, If A is paired with F, F can NOT be paired with A. So there will have to be as many relationships as there are items.

推荐答案

这个怎么样?

// input array
$arr = array('A','B','C','D','E','F');
// 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;

print_r($res);

输出:

Array
(
    [A] => B
    [B] => F
    [F] => E
    [E] => D
    [D] => C
    [C] => A
)

工程与偶数个元素的数组,以及奇。

Works with even number of elements arrays as well as odd.

更新,使用Chris的算法:

Update, using Chris' algorithm:

$arr = array('A','B','C','D','E','F');
shuffle($arr);
$res=array();
for($i=0;$i<count($arr);$i++) {
  $res[$arr[$i]] = $arr[$i+1];
}
$res[$arr[count($arr)-1]] = $arr[0];

这篇关于使用PHP,随机配对组项目,没有任何配对与自己没有直接配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆