从数组访问独特的价值对不重复自己 [英] Accessing unique value pairs from an array without repeating myself

查看:87
本文介绍了从数组访问独特的价值对不重复自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图访​​问唯一值从随机顺序的数组对 - 不重复自己,直到我不得不这样做。

I am trying to access unique value pairs from an array in a random order - without repeating myself until I have to.

例如,如果我有一个数组设置A,B,C,D(通常是偶数项,但最多20个),然后在第一时间通过我可能对A-B和;光盘。但我要保证下一次我这样做,我避免重蹈我的配对,但是我同时获得A-C和; B-D和A-D和B-C之前,我还是那句话得到A-B和C-D。每个项目只应在每一轮调用一次。

For example, if I have an array set A,B,C,D (generally an even number of items, but up to 20) then the first time through I might pair A-B & C-D. But I want to guarantee that the next time I do it, I avoid repeating my pairing and that I get both A-C & B-D and A-D and B-C before I then get A-B and C-D again. Each item should only be called once in each round.

我开始通过洗牌数组的顺序随机配对,然后两个值在一起 - 但我需要比别人(更频繁发生的一些配对的方式,以prevent理想我希望他们能够平等地增加所有的方式,通过)。

I started off by shuffling the order of the array randomly then pairing two values together - but I need a way to prevent some pairings from occurring more frequently than others (ideally I'd want them to increment equally all the way through).

所以我搬到看着排列 - 并设法使用下面的code包含所有可能配对一个完整的数组:

So I've moved to looking at permutations - and have managed to get a full array containing all the possible pairings using the code below:

    $this->items = array('A','B','C','D');

    $input = $this->items;
    $input_copy = $input;
    $output = array();
    $i = 0;
    foreach($input as $val) {

        $j = 0;
        foreach($input_copy as $cval) {
            if($j == $i) break;
            print $val.'-'.$cval.'<br/>';
            //$output[] = array($val => $cval);
            $j++;
        }
        $i++;
    }

    //print_r($output);

例如为A,B,C,D,我得到:

e.g for A, B, C, D I get:

b-a
c-a
c-b
d-a
d-b
d-c

我要循环集合N-1次,捕获另一个数组的结果,但我不知道如何从这些独特的选项的实际顺序

I want to cycle through the set n-1 times and capture the results in another array, but I'm not sure how to generate the actual order from these unique options

在换句话说,我想打开上述列表中的如下:

In other words, I want to turn the list above in to the below:

1st run =>
    1=> A-B, 
    2=> C-D, 
2nd run =>
    1=> A-C, 
    2=> B-D,
3rd run =>
    1=> A-D, 
    2=> C-B,

这可能是我可以更简单地从$这个 - >项目做到这一点。我也有一看Math_Combinatorics PEAR包,但我不知道从哪里开始。

It may be that I can do this more simply from $this->items. I've also had a look at the Math_Combinatorics PEAR package, but I wasn't sure where to start.

我很感谢任何帮助!

推荐答案

您可以使用循环赛赛事算法

Place elements in two rows. 
Fix one element - in this case A
For next round shift all other elements in circular manner. 
Pair them. 
Repeat N-1 times

A B
D C
-----
A D
C B
----
A C
B D
----

这篇关于从数组访问独特的价值对不重复自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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