[英]Completely Unique Combinations of Two Arrays in PHP
I've been struggling with this question for an entire work day I cannot craft a viable solution that doesn't either take huge amounts of memory or take forever to complete.我一整天都在为这个问题苦苦挣扎,我无法制定一个既不占用大量内存又不花很长时间才能完成的可行解决方案。
If I have two arrays:如果我有两个数组:
$letters = array ('a','b','c','d');
$numbers = array (1,2,3,4);
How do I get COMPLETELY unique combinations?我如何获得完全独特的组合? In other words, since these arrays have four elements each, the function should return four combinations ONLY, with each element in the arrays only used once.
换句话说,由于这些数组每个都有四个元素,函数应该只返回四个组合,数组中的每个元素只使用一次。
Example combinations using the arrays above:使用上述数组的示例组合:
a1 b2 c3 d4
a1 b2 c3 d4
-or- -或者-
a2 b4 c3 d1
a2 b4 c3 d1
-or- -或者-
a4 b2 c3 d1
a4 b2 c3 d1
...etc... ...等等...
All of the examples I find do not take uniqueness of both arrays into account.我发现的所有示例都没有考虑两个数组的唯一性。 Answers like this are not valid:
像这样的答案无效:
a1 b2 c3 d3
a1 b2 c3 d3
-or- -或者-
a3 b2 c3 d2
a3 b2 c3 d2
I'm having a hell of a time crafting a function that works properly.我正在忙着制作一个可以正常工作的函数。
Given the arrays are both of equal length as in your example, maybe something like this, using shuffle :鉴于数组的长度与您的示例中的长度相同,使用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 )
Another possibility without shuffling the arrays beforehand (not that there's anything wrong with that; just a different approach):另一种不预先改组数组的可能性(并不是说这有什么问题;只是一种不同的方法):
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.