PHP中两个数组的完全唯一组合


Completely Unique Combinations of Two Arrays in PHP

我已经为这个问题纠结了整整一天,我无法想出一个既不占用大量内存又不需要永远完成的可行解决方案。

如果我有两个数组

$letters = array ('a','b','c','d');
$numbers = array (1,2,3,4);

如何获得完全唯一的组合?换句话说,由于这些数组每个都有四个元素,该函数应该只返回四个组合,数组中的每个元素只使用一次。

使用上述数组的组合示例:

a1 b2 c3 d4

或者

a2 b4 c3 d1

或者

a4 b2 c3 d1

…等…

我找到的所有例子都没有考虑到两个数组的唯一性。像这样的答案是无效的:

a1 b2 c3 d3

或者

a3 b2 c3 d2

我花了很长时间来设计一个能正常工作的函数

假设两个数组的长度都是相等的,就像在您的示例中一样,可能像这样,使用shuffle:

<?php
$letters = array ('a','b','c','d');
$numbers = array (1,2,3,4);
function randmix($a, $b){
    shuffle($a);
    shuffle($b);
    foreach($a as $i => $val){
        $product []= $val.$b[$i];
    }
    return $product;
}
print_r(randmix($letters,$numbers));
Array
(
    [0] => d1
    [1] => a3
    [2] => c4
    [3] => b2
)

另一种不需要事先打乱数组的可能性(这并不是说有什么问题;只是一种不同的方法):

while ($letters && $numbers) {              // keep going as long as both arrays have values
    $combination = '';
    foreach ([&$letters, &$numbers] as &$array) {
        // select a random element from each array and then unset it
        $key = array_rand($array);
        $combination .= $array[$key];
        unset($array[$key]);
    }
    $combinations[] = $combination;
}