For example, this is the input array: [2, 1, 4, 4, 3]
From this array, n-1 patterns will be established from left to right.
This output would be the number 7
because the following separate arrays exist after grouping:
[2] [1] [4] [4] [3]
– 1 group (n)
[4, 3]
– 1 group (n-1)
[2, 1]
– 1 group (n-1)
Output: 7
(arrays)
This is what I started so far, but it looks like I just summed everything together.
JavaScript
x
7
1
let numbers = [2, 1, 4, 4, 3];
2
let sum = numbers.reduce(function (previousValue, currentValue) {
3
return previousValue + currentValue;
4
});
5
6
console.log(sum);
7
It would be appreciated if the solution and an explanation is provided in JavaScript. Thank you!
Advertisement
Answer
Script:
JavaScript
1
8
1
function myFunction() {
2
let numbers = [2, 1, 4, 4, 3];
3
// remove duplicates
4
let unique = [new Set(numbers)];
5
// get length of unique array, then add to the length of filtered unique array where it also contains n-1
6
console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
7
}
8
Get the number of unique elements then add it to the length of the filtered unique array where it also contains n-1
.
Output:
If you want to get the arrays:
JavaScript
1
14
14
1
function myFunction() {
2
let numbers = [2, 1, 4, 4, 3];
3
let unique = [new Set(numbers)];
4
var arrays = [];
5
unique.forEach(number => {
6
arrays.push([number]);
7
if(numbers.includes(number - 1))
8
arrays.push([number, number-1])
9
});
10
11
console.log(arrays.length)
12
console.log(arrays)
13
}
14