问题描述
我正在尝试编写一个将数组和n作为参数的函数,
I am trying to write a function that will take an array and n as parameters,
它将返回该数组的所有子集,其中包含n个元素,
it will return all subsets of that array with n elements, have tried a couple things, couldn't yet succeed.
由于有人把它放在这里,所以此功能太复杂了,无法完成工作,基本上是我试图做到的这里要做的是从4个元素的数组中挑选一个元素来创建其3个元素的子集。甚至都不需要N作为参数。它返回所有3个元素子集,但也返回相同的子集,因此我也必须将它们过滤掉,无论如何我都会继续尝试。
thanks to whoever put it here, this functions is way too complicated and doesn't do the job, basically what I tried to do here is to pick out one element from a 4 element array to create its 3 element subsets. It doesn't even take N as parameter. it returns all 3 element subsets but also identical ones, so I have to filter them out as well, in any case I will keep trying.
function findSubsets(array) {
var answers = [];
var firstArray = array;
for (i = 0; i < array.length; i++) {
array = firstArray;
for (var k = 0; k < array.length; k++) {
if (k != i) {
var subset = array.splice(k, 1);
answers.push(array); array.splice(k, 0, subset[0]);
}
}
}
}
推荐答案
您可以尝试此解决方案
var subsetArray = (function() {
return {
getResult: getResult
}
function getResult(array, n) {
function isBigEnough(value) {
return value.length === n;
}
var ps = [
[]
];
for (var i = 0; i < array.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(array[i]));
}
}
return ps.filter(isBigEnough);
}
})();
var arr = [1、2、3、4、5、6、7、8、9 ];
console.log(subsetArray.getResult(arr,2));
var arr = [1, 2, 3, 4,5,6,7,8,9];console.log(subsetArray.getResult(arr,2));
这篇关于具有n个元素的数组的子集javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!