Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript组合方法_Javascript_Algorithm_Combinations - Fatal编程技术网

Javascript组合方法

Javascript组合方法,javascript,algorithm,combinations,Javascript,Algorithm,Combinations,我需要帮助来构建获得两个参数的函数:“chars”,“combinationLength” 例如: var chars = [1,2,3,4,5,6]; //can be also strings var combinationLength = 3; generateCombinations(chars, combinationLength){ } 输出应为: 111 112 113 114 115 116 121 122 等等 这意味着接受所有字符并创建组合, 希望我很清楚;] 您可

我需要帮助来构建获得两个参数的函数:“chars”,“combinationLength” 例如:

 var chars = [1,2,3,4,5,6]; //can be also strings
 var combinationLength = 3;
 generateCombinations(chars, combinationLength){
 }
输出应为: 111 112 113 114 115 116 121 122 等等

这意味着接受所有字符并创建组合,
希望我很清楚;]

您可以使用迭代和递归方法,使用临时数组和长度检查

函数生成组合(数组、长度){
var结果=[];
array.forEach(函数iter(a){
var r=此。concat(a);
如果(r.length==长度){
结果:推(r);
返回;
}
forEach(iter,r);
}, []);
返回结果;
}
log(generateCombinations([1,2,3,4,5,6,3])

.as控制台包装{max height:100%!important;top:0;}
如果您不想自己编写代码,请查看以下要点

如果您正在Node.js中寻找解决方案,可以使用此库,
. 或者从库中提取所需的函数

Nina Scholz感谢您的回复

函数生成组合(数组、长度){
var结果=[];
array.forEach(函数iter(a){
var r=此。concat(a);
如果(r.length==长度){
结果:推(r);
返回;
}
forEach(iter,r);
}, []);
返回结果;
}
log(generateCombinations([1,2,3,4,5,6,3])

.as控制台包装{max height:100%!important;top:0;}
这不是免费的代码编写服务。。。这取决于您如何显示您的尝试,这里的人会帮助您修复代码