# js:求一个数字组合函数，譬如0-9这10个数字按3个3个组合，列出所有的组合，同数字不同顺序组合按一个组合算

0

function group(a, b){

/*

*/

};

var r = group([1,2,3],2);

r == [[1,2],[1,3],[2,3]];

sc2013 | 初学一级 | 园豆：157

1

```function group(nu, groupl, result){

var result = result ? result : [];
var nul = nu.length;
var outloopl = nul - groupl;

var nuc = nu.slice(0);

var item = nuc.shift();
item = item.constructor === Array ? item : [item];

(function func(item,nuc){
var itemc;
var nucc = nuc.slice(0);
var margin = groupl- item.length

if( margin == 0){
result.push(item);
return;
}
if( margin == 1){
for(var j in nuc){
itemc = item.slice(0);
itemc.push(nuc[j]);
result.push(itemc);
}
}
if( margin > 1){
itemc = item.slice(0);
itemc.push(nucc.shift());
func(itemc,nucc);

if(item.length + nucc.length >= groupl){
func(item,nucc);
}

}

})(item,nuc);

if(nuc.length >= groupl){
return group(nuc, groupl, result);
}else{
return result;
}

}

var arr = group([[1,2],3,4,5],4);
var arr2 = group([1,2,3,4],3);

```

Julien198414 | 菜鸟二级 |园豆：231 | 2013-11-20 18:25

0

```<script type="text/javascript">
function zuhe(array, num) {
var arraySize = array.length;
var res="";
if (0 > num || num > arraySize) {
return;
}

var loop = 0;
var numZuhe = 0;
var stopCondNum = 0;
var currIdx = num - 1;
var changeIdx = num - 1;
var arrayIdx = new Array(array.length); //(int *)malloc(num * sizeof(int));
var isChanged = true;

if (null == arrayIdx) {
return;
}

for (loop = 0; loop < num; ++loop) {
arrayIdx[loop] = loop;
}

while (1) {
var loop = 0;
var stopCondNum = 0;

if (isChanged) {
var tem = "";
for (loop = 0; loop < num; ++loop) {
tem += array[arrayIdx[loop]];

}
++numZuhe;
res += "[" + tem + "]";
}

// 判断终止条件
for (loop = 0; loop < num; ++loop) {
if (arrayIdx[num - loop - 1] == arraySize - loop - 1) {
++stopCondNum;
}
else {
break;
}
}
if (num == stopCondNum) {
break;
}

// 当前位已经达到最大值
if (arrayIdx[currIdx] == arraySize - num + currIdx) {
if (changeIdx == currIdx) // 是否变化到最左侧位数
{
changeIdx--;
currIdx = num - 1;
arrayIdx[changeIdx] = arrayIdx[changeIdx] + 1;
for (loop = changeIdx + 1; loop < num; ++loop) {
arrayIdx[loop] = arrayIdx[loop - 1] + 1;
}

isChanged = true;
}
else {
currIdx--;

isChanged = false;
}
}
else {
arrayIdx[currIdx] = arrayIdx[currIdx] + 1;
isChanged = true;
}
}
return res;
}

</script>搞定，网上找个c++的代码帮你翻译过来的 哈哈```

@sc2013: julien198414  非常值得学习

@大芝麻: 是算法的问题吗，这方法有bug

@大芝麻:

@大芝麻: 截不了图，你用group('123456',3)试试，20个才是正确的

0

您需要登录以后才能回答，未注册用户请先注册