如何使用 n 个元素的数组中的重复项创建排列子数组?
How make an sub-array of permutations with duplicates from array of n elements?
我尝试使用一个数组来迭代组合数组中 n 个元素的所有可能性:
array = ["9","0","1","2"];
例如函数 combine(array,iter)
和 iter=2
应该 return:
["90","09","91","19","92","29","01","10","02","20","12","21","99","00","11","22"]
参数定义:
array: original array with all elements to combine.
iter: number of elements to result in combine with duplicates.
我尝试使用yield,但是没有结果,元素的数量是正确的,但是值是错误的:
//Thank you to le_m for the code in ES6!
function* express(tokens, size) {
if (size < 1) yield [];
else
for (var item of tokens) {
for (var combination of express(tokens, size - 1)) {
yield combination.concat(item);
}
}
}
array = ["9","0","1","2"];
for (iter of express(array,2)) {
console.log(iter)
}
Console Output:
[ '9', '9' ]
[ '0', '9' ]
[ '1', '9' ]
[ '2', '9' ]
[ '9', '0' ]
[ '0', '0' ]
[ '1', '0' ]
[ '2', '0' ]
[ '9', '1' ]
[ '0', '1' ]
[ '1', '1' ]
[ '2', '1' ]
[ '9', '2' ]
[ '0', '2' ]
[ '1', '2' ]
[ '2', '2' ]
您想生成给定长度的所有可能组合。总共有 n^length 种组合。为了避免可能的巨大内存需求,我建议使用 a generator function:
// Return all combinations of 'length' elements from array:
function* combine(array, length) {
if (length < 1) yield [];
else for (let element of array) {
for (let combination of combine(array, length - 1)) {
yield combination.concat(element);
}
}
}
// Example:
console.log(...combine(["9", "0", "1", "2"], 2));
我尝试使用一个数组来迭代组合数组中 n 个元素的所有可能性:
array = ["9","0","1","2"];
例如函数 combine(array,iter)
和 iter=2
应该 return:
["90","09","91","19","92","29","01","10","02","20","12","21","99","00","11","22"]
参数定义:
array: original array with all elements to combine.
iter: number of elements to result in combine with duplicates.
我尝试使用yield,但是没有结果,元素的数量是正确的,但是值是错误的:
//Thank you to le_m for the code in ES6!
function* express(tokens, size) {
if (size < 1) yield [];
else
for (var item of tokens) {
for (var combination of express(tokens, size - 1)) {
yield combination.concat(item);
}
}
}
array = ["9","0","1","2"];
for (iter of express(array,2)) {
console.log(iter)
}
Console Output:
[ '9', '9' ]
[ '0', '9' ]
[ '1', '9' ]
[ '2', '9' ]
[ '9', '0' ]
[ '0', '0' ]
[ '1', '0' ]
[ '2', '0' ]
[ '9', '1' ]
[ '0', '1' ]
[ '1', '1' ]
[ '2', '1' ]
[ '9', '2' ]
[ '0', '2' ]
[ '1', '2' ]
[ '2', '2' ]
您想生成给定长度的所有可能组合。总共有 n^length 种组合。为了避免可能的巨大内存需求,我建议使用 a generator function:
// Return all combinations of 'length' elements from array:
function* combine(array, length) {
if (length < 1) yield [];
else for (let element of array) {
for (let combination of combine(array, length - 1)) {
yield combination.concat(element);
}
}
}
// Example:
console.log(...combine(["9", "0", "1", "2"], 2));