数组中所有可能的组合-递归? [英] All possible combinations in array - recursion?
问题描述
我有一个想不通的问题,希望有人能提供帮助.我认为可能必须通过递归和/或置换来解决,但是我对于(PHP)程序员来说还不够好.
I have a question that goes over my head, hope someone can help. I think it may have to be solved by recursion and/or permutations, but I am not good enough of a (PHP) programmer for that.
$map[] = array("0", "1", "2", "3");
$map[] = array("4", "5", "6", "7");
$map[] = array("8", "9", "10", "11");
$map[] = array("12", "13", "14", "15");
$map[] = array("16", "17", "18", "19");
$map[] = array("20", "21", "22", "23");
$ map数组的最大长度限制为"6".
The $map array is limited to a max length of "6".
我正在寻找一种方法来进行所有可能的组合.以下是一些有效的组合:
I am looking for a way to make all possible combinations. Here are a few VALID combinations:
示例1:
$map[] = array("0", "1", "2", "3", "4", "5", "6", "7");
$map[] = array("8", "9", "10", "11");
$map[] = array("12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", );
$map[] = array("23");
示例2:
$map[] = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23");
示例3:
$map[] = array("0", "1");
$map[] = array("2", "3", "4", "5", "6", "7", "8");
$map[] = array("9", "10", "11");
$map[] = array("12");
$map[] = array("13", "14", "15", "16", "17", "18", "19", "20");
$map[] = array("21", "22", "23");
每个映射数组中的值必须按升序排列,例如这个例子是无效的:
The values in each of the map arrays have to be in ascending order, e.g. this example is INVALID:
$map[] = array("0", "1", "4");
$map[] = array("3", "5");
etc...
希望可以做到.
推荐答案
递归解决方案.
<?php
function combination($remaining, $current, $combinations) {
$e = array_shift($remaining);
$combinations[$current][] = $e;
if(empty($remaining)) {
print_r($combinations);
return;
}
combination($remaining, $current, $combinations);
// 6 Limit remove for all solutions
if ($current < 6) {
combination($remaining, $current + 1, $combinations);
}
}
$remaining = range(0, 23);
combination($remaining, 0, array());
如果您想存储[0,23]的所有解决方案,那将是一段糟糕的时光.
If you want to store all solutions for [0,23] you're gonna have a bad time.
这篇关于数组中所有可能的组合-递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!