为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森栏 2019-08-27 18:16:31
PHP算法从单个集合生成特定大小的所有组合我试图推导出一种算法,该算法生成特定大小的所有可能组合,例如接受字符数组和大小作为参数的函数,并返回组合数组。示例:假设我们有一组字符:设置A = {A,B,C}a)尺寸2的所有可能组合:(3 ^ 2 = 9)AA, AB, ACBA, BB, BCCA, CB, CCb)尺寸3的所有可能组合:(3 ^ 3 = 27)AAA, AAB, AAC,ABA, ABB, ACC,CAA, BAA, BAC,.... ad so on total combinations = 27请注意,货币对的大小可能大于pouplation的总大小。防爆。如果set包含3个字符,那么我们也可以创建大小为4的组合。编辑:另请注意,这与排列不同。在排列中我们不能有重复的字符,例如,如果我们使用置换算法,AA就不会出现。在统计中,它被称为抽样。
查看完整描述

3 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

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

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"
}
*/


查看完整回答
反对 回复 2019-08-27
?
千巷猫影

TA贡献1829条经验 获得超7个赞

一种可能的算法是:

$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')依此类推。


查看完整回答
反对 回复 2019-08-27
  • 3 回答
  • 0 关注
  • 544 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信