产生不同的组合PHP [英] Generate Distinct Combinations PHP

查看:133
本文介绍了产生不同的组合PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个高效的算法来生成不同的组合(不允许重复)。每个组合具有5 distint号(不同的号码),该范围在1和99的结果必须被存储在数组中。如果可能的话,我想允许定制的数量和范围。数字的顺序并不重要(01 02 03 = 03 01 02)

I need an efficient algorithm to generate distinct combinations(not allowed to repeat). Each combination has 5 distint numbers(different numbers) that ranges between 1 and 99. The result must be stored in an array. If possible I would like the numbers and range allowed to be customized. The order of number doesn't matter(01 02 03 = 03 01 02)

 Ex.: 
 01 02 03 04 05
 02 03 04 05 06
 ...

有谁可以帮我建了吗?我想拿起从数组一些随机组合。 Nowdays我产生随机组合使用mt_rand但它需要太多的时间,这么慢!我相信发生如此频繁重复再花费时间来生成新的,新的...

Does anyone could help me to build it? I would like to pick up some random combinations from the array. Nowdays I am generating random combinations using mt_rand but It takes too much time, SO SLOW! I believe happens to repeat so often then takes time to generate new one and new one...

推荐答案

下面是简单的code,它应该运行相当快,做你的描述。

Here's the simple code that should run rather fast and do what you describe.

$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));

请注意:当你需要一些组合,它仅适用。你不说出你想要的所有的可能的,所以我想,如果你需要的只是一群人 - 这里是非常简单快捷的方法来做到这一点。

Note: it only works when you need a few combinations. You don't state that you want all of the possible ones, so I thought if you need just a bunch of them - here's very quick and easy way to do it.

有关有点慢(你产生更多的 - 它会较慢),但生成的任何套​​量,你可以使用这个code

For a bit slower (the more you generate - the slower it goes), but that generates any amount of sets, you can use this code.

$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);

这篇关于产生不同的组合PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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