【发布时间】:2023-03-24 16:15:01
【问题描述】:
我有一个Array 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 中做到这一点吗?
【问题讨论】:
-
迭代数组,递增索引,按顺序抓取3个元素,不越界。
-
只需迭代直到
a.length - 3,并在每次迭代时将a.slice(i, i + 3)推送到结果。
标签: javascript arrays combinations combinatorics