PHP 算法,用于从单个集合生成特定大小的所有组合


PHP algorithm to generate all combinations of a specific size from a single set

我正在尝试推断一种算法,该算法生成特定大小的所有可能组合,例如接受字符数组和大小作为其参数并返回组合数组的函数。

例:假设我们有一组字符:集合 A = {A,B,C}

a) 大小 2 的所有可能组合:(3^2 = 9)

AA, AB, AC
BA, BB, BC
CA, CB, CC

b) 大小 3 的所有可能组合:(3^3 = 27)

AAA, AAB, AAC,
ABA, ABB, ACC,
CAA, BAA, BAC,
.... ad so on total combinations = 27

请注意,货币对大小可以大于 pouplation 的总大小。 例如,如果 set 包含 3 个字符,那么我们也可以创建大小为 4 的组合。

编辑:另请注意,这与排列不同。在排列中,我们不能有重复的字符,例如,如果我们使用排列算法,AA 就不能来。在统计学中,它被称为抽样。

我会使用递归函数。这是一个带有注释的(工作)示例。希望这对你有用!

function sampling($chars, $size, $combinations = array()) {
    # if it's the first iteration, the first set 
    # of combinations is the same as the set of characters
    if (empty($combinations)) {
        $combinations = $chars;
    }
    # we're done if we're at size 1
    if ($size == 1) {
        return $combinations;
    }
    # initialise array to put new values in
    $new_combinations = array();
    # loop through existing combinations and character set to create strings
    foreach ($combinations as $combination) {
        foreach ($chars as $char) {
            $new_combinations[] = $combination . $char;
        }
    }
    # call same function again for the next iteration
    return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);
/*
array(9) {
  [0]=>
  string(2) "aa"
  [1]=>
  string(2) "ab"
  [2]=>
  string(2) "ac"
  [3]=>
  string(2) "ba"
  [4]=>
  string(2) "bb"
  [5]=>
  string(2) "bc"
  [6]=>
  string(2) "ca"
  [7]=>
  string(2) "cb"
  [8]=>
  string(2) "cc"
}
*/

可能的算法是:

$array_elems_to_combine = array('A', 'B', 'C');
$size = 4;
$current_set = array('');
for ($i = 0; $i < $size; $i++) {
    $tmp_set = array();
    foreach ($current_set as $curr_elem) {
        foreach ($array_elems_to_combine as $new_elem) {
            $tmp_set[] = $curr_elem . $new_elem;
        }
    }
    $current_set = $tmp_set;
}
return $current_set;

基本上,你要做的是获取当前集合的每个元素并附加元素数组的所有元素。

第一步:你将得到结果('a', 'b', 'c'),在第二步之后:('aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc')等等。

您可以递归执行此操作。请注意,根据您的定义,长度n+1的"组合"可以从长度n的组合中生成,方法是将长度的每个组合n并从集合中附加一个字母。如果你关心,你可以通过数学归纳来证明这一点。

例如,对于一组{A,B,C}长度为 1 的组合是:

A, B, C

因此,长度 2 的组合是

(A, B, C) + A = AA, BA, CA
(A, B, C) + B = AB, BB, BC
(A, B, C) + C = AC, CB, CC

这将是代码,在 ideone 上

function comb ($n, $elems) {
    if ($n > 0) {
      $tmp_set = array();
      $res = comb($n-1, $elems);
      foreach ($res as $ce) {
          foreach ($elems as $e) {
             array_push($tmp_set, $ce . $e);
          }
       }
       return $tmp_set;
    }
    else {
        return array('');
    }
}
$elems = array('A','B','C');
$v = comb(4, $elems);

这是一个朋友制作的代码,它从数字列表中生成了 X 个数字的唯一组合。

如果你有一个数字列表,比如1,3,4,7,12,你可以生成X数字集,都是唯一的,没有重复的。

第一个函数适用于 PHP 7.4 或更高版本,第二个函数使用键来存储值。基于基准测试,两者都运行良好。

function get_combos74($map, $size, &$generated = [], $loop = 1, $i = 0, $prefix = [])
{
    if ($loop == 1) {
        sort($map);
    }
    for (; $i < count($map); $i++) {
        if ($loop < $size) {
            get_combos74($map, $size, $generated, $loop + 1, $i + 1, [...$prefix, $map[$i]]);
        } else {
            $generated[] = [...$prefix, $map[$i]];
        }
    }
    return $generated;
}
function get_combosSTR($map, $size, &$generated = [], $loop = 1, $i = 0, $prefix = '')
{
    if ($loop == 1) {
        sort($map);
    }
    for (; $i < count($map); $i++) {
        if ($loop < $size) {
            get_combosSTR($map, $size, $generated, $loop + 1, $i + 1, "$prefix{$map[$i]}:");
        } else {
            $generated["$prefix{$map[$i]}"] = 0;
        }
    }
    return $generated;
}

使用数字基数转换的另一个想法

$items = ['a', 'b', 'c', 'd'];
$length = 3;
$numberOfSequences = pow(count($items), $length);
for ($i = 0; $i < $numberOfSequences; $i++) {
    $results[] = array_map(function ($key) use ($items) {
        return $items[base_convert($key, count($items), 10)];
    }, str_split(str_pad(base_convert($i, 10, count($items)), $length, 0, STR_PAD_LEFT)));
}
return $results;