例如,这是输入数组:[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 (数组)
到目前为止,这就是我所开始的,但看起来我只是把所有的东西汇总在一起。
let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
});
console.log(sum);如能在JavaScript中提供解决方案和解释,将不胜感激。谢谢!
发布于 2022-04-29 00:55:56
剧本:
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。
输出:

如果您想获得数组:
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)
}

https://stackoverflow.com/questions/72051585
复制相似问题