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.
let numbers = [2, 1, 4, 4, 3]; let sum = numbers.reduce(function (previousValue, currentValue) { return previousValue + currentValue; }); console.log(sum);
It would be appreciated if the solution and an explanation is provided in JavaScript. Thank you!
Advertisement
Answer
Script:
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); }
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:
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) }