简体   繁体   English

所有组合都没有重复,具有特定的基数

[英]All combinations without repetitions with specific cardinality

I have an array: 我有一个数组:

[a, b, c, d, e, f, ... , z]

and I would generate the set of all possible subarrays, withuout repetition, whose cardinality is between X and Y. 然后我将生成所有可能的子数组的集合,并且没有重复,其基数在X和Y之间。

Let's assume php: 我们假设php:

$array = array(1, 2, 3, 4, 5, 6, 7, 8);

$results = myFunction($array, 3, 5);

My function should returns something like: 我的函数应返回如下内容:

array( 
    array(1, 2, 3),
    array(1, 2, 4),
    ...
    array(4, 5, 6, 7, 8),
);

My attempt was to count in binary, from 0 to 2^n (where n is the cardinality of the set) and if the number of 1s is between X and Y, add the array made of 1s element to the result set. 我的尝试是在二进制计数,从0到2 ^ n(其中n是该集合的基数),如果数量1s是X和Y之间,添加制成的阵列1s元件到结果集。

Eg. 例如。

8  = 0000 0111 => add (6,7,8) to result
9  = 0000 1000 => no 
10 = 0000 1001 => no
...

but it's very ugly! 但它非常难看! Any better algorithm? 有更好的算法吗?

I'm using php, but feel free to use whatever language you like. 我正在使用PHP,但随意使用你喜欢的任何语言。

A pretty straightforward solution (requires generators, I think, it's php 5.5+) 一个非常简单的解决方案(需要生成器,我认为,这是PHP 5.5+)

// generate combinations of size $m
function comb($m, $a) {
    if (!$m) {
        yield [];
        return;
    }
    if (!$a) {
        return;
    }
    $h = $a[0];
    $t = array_slice($a, 1);
    foreach(comb($m - 1, $t) as $c)
        yield array_merge([$h], $c);
    foreach(comb($m, $t) as $c)
        yield $c;
}

and then 接着

$a = ['a','b','c','d','e','f', 'g'];

foreach(range(3, 5) as $n)
    foreach(comb($n, $a) as $c)
        echo join(' ', $c), "\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM