【发布时间】:2017-12-26 11:13:36
【问题描述】:
我正在尝试从一个数字数组中生成所有有效的数字组合。假设我们有以下内容:
let arr = [1, 2, 9, 4, 7];
我们需要输出如下内容:
1 2 9 4 7
1 2 9 47
1 2 94 7
1 2 947
1 29 4 7
1 29 47
1 294 7
1 2947
12 9 4 7
12 9 47
12 94 7
12 947
129 4 7
129 47
1294 7
12947
无效的数字是 91、497、72 等等。
我试过了,但我对结果不满意:
const combination = (arr) => {
let i, j, temp;
let result = [];
let arrLen = arr.length;
let power = Math.pow;
let combinations = power(2, arrLen);
for (i = 0; i < combinations; i += 1) {
temp = '';
for (j = 0; j < arrLen; j++) {
if ((i & power(2, j))) {
temp += arr[j];
}
}
result.push(temp);
}
return result;
}
const result = combination([1, 2, 9, 4, 7]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
有什么想法吗?
【问题讨论】:
-
不满意?您需要说明您遇到的问题或错误。
-
你想用这个问题解决什么问题?
-
checkout github.com/dankogai/js-combinatorics - 你可能会找到适合排列的方法
-
@Xufox 你的代码完全符合我的要求。谢谢。但很难理解它是如何工作的。
-
@AlexandarTargov 我已经在答案中解释过了。
标签: javascript combinations combinatorics