我有一个数组 a = [0,1,2,3,4,5,6]
我想用 3 个元素进行子集化,这样结果就变成了这样:
[0,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,6]
我尝试使用我发现的这个脚本:
Array.prototype.combinate = function( iItems, aIn ) {
if (!aIn) {
var aIn = new Array();
this.combinate.aResult = new Array();
}
for(var i = 0; i < this.length; i++) {
var a = aIn.concat(this[i]);
var aRest = this.concat(); // Concat with nothing to create copy
aRest.splice(0, i + 1);
if(iItems && iItems - 1 <= aRest.length) {
aRest.combinate(iItems - 1, a);
if(iItems == 1) this.combinate.aResult.push(a);
}
}
return this.combinate.aResult;
}
但这给出了所有可能的子集(当列表变大而搜索子集很小时,很容易变慢) - 我只需要像上面所示的“顺序”子集 - 就像 [1,2,3 ]
可以 - 但不是[1,2,4]
..
有哪位聪明人知道如何在 JavaScript 中做到这一点..?
最佳答案
假设有问题的数组不需要首先以某种方式排序,我会这样做:
function combinate(arr) {
var results = [];
if (arr.length >= 3) {
for (var i = 0; i < arr.length - 2; i++) {
var slice = arr.slice(i, i + 3);
results.push(slice);
}
}
return results;
}
作为补充说明,我建议不要将类似的内容作为方法添加到数组原型(prototype)中。如果您出于某种原因需要这样做,没有什么可以阻止您这样做,但我会避免这样做。
关于javascript - 在 Javascript 中列出顺序子集元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478278/