PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] How do you group an array by n and the number of decreasing integers (n-1)? With the output to be the total number of arrays

 August 14, 2022     arrays, group, javascript, output, sorting     No comments   

Issue

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!


Solution

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:

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)
}

output2



Answered By - NightEye
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing