首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将数组按n和递减整数(n-1)的数目分组?的输出是数组的总数。

如何将数组按n和递减整数(n-1)的数目分组?的输出是数组的总数。
EN

Stack Overflow用户
提问于 2022-04-29 00:29:12
回答 1查看 111关注 0票数 1

例如,这是输入数组:[2, 1, 4, 4, 3]

从这个数组,n-1模式将从左到右建立.

这个输出将是数字7,因为在分组后存在以下单独的数组:

[2] [1] [4] [4] [3] -1群(n)

[4, 3] -1群(n-1)

[2, 1] -1群(n-1)

输出:7 (数组)

到目前为止,这就是我所开始的,但看起来我只是把所有的东西汇总在一起。

代码语言:javascript
运行
复制
let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);

如能在JavaScript中提供解决方案和解释,将不胜感激。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-29 00:55:56

剧本:

代码语言:javascript
运行
复制
function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  // remove duplicates
  let unique = [...new Set(numbers)];
  // get length of unique array, then add to the length of filtered unique array where it also contains n-1
  console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
}

获取唯一元素的数量,然后将其添加到筛选后的唯一数组的长度中,其中还包含n-1

输出:

如果您想获得数组:

代码语言:javascript
运行
复制
function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  let unique = [...new Set(numbers)];
  var arrays = [];
  unique.forEach(number => {
    arrays.push([number]); 
    if(numbers.includes(number - 1))
      arrays.push([number, number-1])
  });

  console.log(arrays.length)
  console.log(arrays)
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72051585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档