我试图让这个函数将数组分割成子集。每个子集的数字都等于前一个子集或与前一个子集相差 1 以内。 下面的示例应该返回两个子集,但它返回的是 {0, 1, 2, 3}。知道我做错了什么吗?另外,是否有更好的方法为每个新子集动态创建数组?谢谢
function max_tickets() {
var arr = [4, 13, 2, 3];
var myarr = arr.sort(function(a, b){return a-b});
for(var i = 0; i<myarr.length; i++){
var iplus = i+1;
if(i === i || i === iplus){
newArr= [];
newArr.push(i);
}else if (i !== i || i !== iplus){
arr2 =[];
arr2.push(i);
}
}
}
最佳答案
您尝试执行的操作通常称为“分区”。问题的通用版本是使用一些“规则”、谓词或条件将数组划分为子数组,这些“规则”或谓词或条件指定特定元素应该进入哪个分区,或者指定它应该进入新分区.
执行此操作的伪代码是:
To partition an array:
Initialize the resulting array
For each element in the array
If that element starts a new chunk
Create a new empty chunk in the resulting array
Add the element to the most recent chunk
Return the result
这可以在 JS 中非常简单地表达为
function partition(array, fn) {
return array.reduce((result, elt, i, a) => {
if (!i || !fn(elt, i, a)) result.push([]);
result[result.length - 1].push(elt);
return result;
}, []);
}
现在我们需要编写函数来说明何时启动新分区:
// Is the element within one of the previous element?
function close(e, i, a) {
return Math.abs(e - a[i-1]) > 1;
}
我们现在可以使用以下命令对数组进行分区
partition([[4, 13, 2, 3], close)
关于javascript - 将数组分解为子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525638/