英文:
How can I get all k-length combinations of an n-length array in JavaScript?
问题
以下是代码的翻译部分:
我有这个问题,*https://stackoverflow.com/questions/75598430/how-to-generate-all-possible-melody-strings-for-this-melody-generator-minus-the*,但也许它可以简化为子问题,比如这个当前的问题。
在这里,我想知道如何取一个长度为 `n` 的数组,然后找到所有长度为 `k` 的元素的组合。
举个例子,你有这样一个数组:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
而你想找到所有长度为4的子数组的组合,就像这样:
[ 1, 2, 3, 4 ]
[ 2, 3, 4, 5 ]
...
[ 1, 2, 4, 5 ]
...
[ 1, 2, 3, 6 ]
你该如何在 JavaScript 中实现这个?我一开始就感到迷茫:
```javascript
function getCombinations(k, n) {
const array = new Array(n)
array.forEach((x, i) => {
array[i] = i + 1
})
const results = []
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
let l = k
const result = []
while (l--) {
result.push(j) // ???
}
}
}
}
希望这对你有所帮助。如果需要更多解释或帮助,请告诉我。
英文:
I have this question, https://stackoverflow.com/questions/75598430/how-to-generate-all-possible-melody-strings-for-this-melody-generator-minus-the, but perhaps it can be simplified into subproblems, such as this current question.
Here, I am wondering how to take an array of length n
and find all combinations of k
number of elements.
So for example, you have an array like this:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
And you want to find all combinations of length-4 subarrays which would be something like this:
[ 1, 2, 3, 4 ]
[ 2, 3, 4, 5 ]
...
[ 1, 2, 4, 5 ]
...
[ 1, 2, 3, 6 ]
How would you do that in JavaScript? I get lost right away:
function getCombinations(k, n) {
const array = new Array(n)
array.forEach((x, i) => {
array[i] = i + 1
})
const results = []
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
let l = k
const result = []
while (l--) {
result.push(j) // ???
}
}
}
}
答案1
得分: 3
我建议将创建数组的逻辑与从数组中获取组合的逻辑拆分成两个不同的函数。
对于获取组合,你可以考虑使用一个生成器函数:
const sequence = (length) => Array.from({length}, (_, i) => i + 1);
function* getCombinations(array, k, taken=[]) {
if (k == 0) return yield taken;
if (array.length < k) return;
yield* getCombinations(array.slice(1), k - 1, taken.concat(array[0]));
yield* getCombinations(array.slice(1), k, taken);
}
const combis = [...getCombinations(sequence(6), 4)];
console.log(combis);
请注意,以上是你提供的代码的翻译部分。
英文:
I would suggest splitting the logic for creating the array from getting combinations from it into two different functions.
For getting combinations, you might want to consider using a generator function:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const sequence = (length) => Array.from({length}, (_, i) => i + 1);
function* getCombinations(array, k, taken=[]) {
if (k == 0) return yield taken;
if (array.length < k) return;
yield* getCombinations(array.slice(1), k - 1, taken.concat(array[0]));
yield* getCombinations(array.slice(1), k, taken);
}
const combis = [...getCombinations(sequence(6), 4)];
console.log(combis);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论