我需要一个高效的算法来生成不同的组合(不允许重复)。每个组合有5个不同的数字(不同的数字),范围在1到99之间。结果必须存储在数组中。如果可能的话,我希望可以自定义数字和范围。编号顺序无关紧要(01 02 03=03 01 02)
Ex.:
01 02 03 04 05
02 03 04 05 06
...
有人能帮我建造它吗?我想从数组中挑选一些随机组合。现在我正在使用mt_rand生成随机组合,但这需要太多时间,太慢了!我相信经常重复,然后需要时间来产生新的和新的。。。
我很快就把这些拼凑起来了,似乎奏效了。
<?php
$range_low = 1;
$range_hi = 99;
$num_sets = 10;
$set = generateSet($range_low, $range_hi, $num_sets);
print_set($set);
function generateSet($range_low, $range_hi, $numSets = 5, $numPerSet = 5)
{
$return = array();
$numbers = array();
for($i = $range_low; $i <= $range_hi; ++$i) {
$numbers[] = $i;
}
for ($s = 0; $s < $numSets; ++$s) {
$set = array_values($numbers);
shuffle($set);
$return[$s] = array();
for ($i = 0; $i < $numPerSet; ++$i) {
$val = array_shift($set);
$return[$s][] = $val;
}
}
return $return;
}
function print_set($set)
{
foreach($set as $subset) {
foreach($subset as $value) {
echo str_pad($value, 2, '0', STR_PAD_LEFT) . ' ';
}
echo "'n";
}
}
样本输出:
90 75 89 43 57
24 54 38 35 10
77 21 55 33 83
37 15 61 09 44
25 31 85 17 20
48 37 45 13 20
82 70 74 64 72
07 24 33 64 45
34 13 39 33 05
13 77 87 70 64
要对Fisher Yates数组进行shuffle,请参阅shuffle上的注释,了解可以用来代替shuffle的函数。
希望能有所帮助。
如果你真的绝对需要一整套所有可能的组合:
function combinations($set,$length) {
$combinations = array();
$setCount = count($set);
for($i = 0, $n = $setCount; $i <= ($n - $length); $i++) {
$combination = array();
$combination[] = $set[$i];
if($length > 1) {
$combination = array_merge(
$combination,
combinations(array_slice($set,1+$i), $length-1)
);
}
$combinations[] = $combination;
}
return $combinations;
}
$allYourNumbers = range(1,99);
$allCombinations = combinations($allYourNumbers, 5);
然后你可以打乱$allCombinations并提取你想要的任意数量,但你需要大量的内存和时间。。。这样做永远不会是有效的
下面是一些简单的代码,它们应该运行得很快,并按照您的描述执行。
$numbers = range(1, 99); // numbers to pick from
$length = 5; // amount of items in the set
$sets_amount = 15; // amount of sets you want to generate
shuffle($numbers); // randomize
function get_set($length, &$numbers) {
return array_splice($numbers, 0, $length);
}
for ($i = 0; $i < $sets_amount; $i++)
print_r(get_set($length, $numbers));
注意:只有当您需要几个组合时,它才有效。你没有说你想要所有可能的,所以我想如果你只需要一堆,这里有一个非常快速简单的方法
如果速度较慢(生成的越多,速度就越慢),但这会生成任何数量的集合,则可以使用此代码。
$numbers = range(1, 99); // numbers to pick from
$length = 5; // amount of items in the set
$sets_amount = 200; // amount of sets you want to generate
$existing = array(); // where we store existing sets
$shuffle_period = count($numbers) - $length - 1; // how often we re-randomize the elements
$j = 0;
for ($i = 0; $i < $sets_amount; $i++, $j++) {
if (!($i % $shuffle_period)) {
shuffle($numbers); // randomize at first go and on $shuffle_period
$j = 0;
}
do {
$arr = array_slice($numbers, $j, $length);
} while (in_array($arr, $existing));
$existing[] = $arr;
}
print_r($existing);