Can you organize an array based on groups of n elements and the number of decreasing integers within each group (n-1)? The goal is to determine the total number of resulting arrays

Consider the input array: [2, 1, 4, 4, 3]

In this array, a total of n-1 patterns can be identified from left to right.

The resulting output will be the number 7 since the arrays are grouped as follows:

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

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

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

Output: 7 (arrays)

This snippet provides an initial attempt where everything is simply summed up together.

let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);

I would appreciate guidance on how to properly solve this problem in JavaScript. Thanks!

Answer №1

Code Sample:

function findUniqueAndRelated() {
  let numbers = [2, 1, 4, 4, 3];
  // Remove duplicates
  let unique = [...new Set(numbers)];
  // Calculate the length of the unique array and add it to the length of filtered unique array containing n-1
  console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
}

Find the number of unique elements and add it to the count of filtered unique elements that also contain n-1.

Result:

https://i.sstatic.net/kCmmr.png

If you want to retrieve the arrays:

function findUniqueAndRelated() {
  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://i.sstatic.net/GGGrp.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for passing parent component state data to a child component using a variable

In my index.js file, I have a parent component with a state variable x:[] that contains data [{…}, {…}, {…}]. Now, in my child component (child.jsx), I need to save this parent component data [{…}, {…}, {…}] in a variable within the child compo ...

Using v-model with an input file is not supported

Is there a solution for not being able to use v-model in an input tag with type="file"? Here is an example of the HTML code causing this issue: <input v-model="imageReference" type="file" name="file"/> ...

Automatically increase the dates in two cells once they have passed

Summary: Although I'm not a programmer, I've managed to incorporate some complex coding into a Google Sheets document for tracking my team's projects. This includes multiple-variable dropdown menus and integration with Google Calendar to mo ...

Would you like to learn how to dynamically alter a button's color upon clicking it and revert it back to its original color upon clicking it again?

My Upvote button starts off transparent, but when I click on it, the background color changes to green. What I need is for the button to become transparent again when clicked a second time. I've attempted using the following code snippet: function ...

Guide on updating the value within nested arrays across multiple documents in MongoDB simultaneously

Looking to update the country value from "India" to something else in multiple documents with the same structure without affecting other keys. Attempted using the Set operator but facing difficulties. { "_id" : "1", "teams ...

What is the process for invoking a server-side code behind method using a JavaScript function in the client side?

I have a JavaScript function that is triggered by the click event of an HTML button on an ASPX page. Additionally, there is a server method located in the code-behind page for handling this functionality. My goal is to invoke the server method from the Jav ...

Regular expression to limit a string to a maximum of 5 consecutive numeric characters and a total of up to 8 numeric characters

I need help creating a regex pattern that limits a string to no more than 5 consecutive numeric characters and a total of 8 numeric characters. Here are some examples: 12345 => True Yograj => True Yograj1234 ...

How to retrieve the initial element from an array using the SimpleXML::xpath function in PHP

Using SimpleXML, I am able to retrieve an element of an XML object by specifying the tag name and attribute like so: $result = $xml->xpath('Stat[@Type="Venue"]'); $venue = $result[0]; Everything runs smoothly with the above code. However.. ...

Ensure that the jQuery datepicker is set with a maximum range of 365 days between the two input fields

Setting Up jQuery Datepicker Inputs I have implemented two jQuery datepicker inputs with default settings as shown below: $("#polis_date_from").datepicker({ uiLibrary: "bootstrap4", changeYear: true, changeMonth: true, dateFormat: "yy.mm.dd", ...

Encountering a 'TypeError: app.address is not a function' error while conducting Mocha API Testing

Facing an Issue After creating a basic CRUD API, I delved into writing tests using chai and chai-http. However, while running the tests using $ mocha, I encountered a problem. Upon executing the tests, I received the following error in the terminal: Ty ...

div added on the fly not showing up

I'm attempting to dynamically add a div to a webpage using Chrome. Despite following several instructional guides, the code does not seem to be working as expected. I have added style attributes to make it more visible, but the element is not showing ...

Is employing the HTML 'confirm' method considered a best practice?

How can I alert a user before they discard changes in a form while switching to another page? Is using if (!confirm("Are you sure")) return false;... considered a good practice for this type of message? Or should I consider using a modal panel instead? (W ...

Display Content in a DIV When Form Field is Unfocused

After hours of searching, I still haven't found a solution! I am trying to create a form field (text) where users can type in text. I want the text they enter to appear in a div on the screen either as they type or after they finish typing. Maybe thi ...

Retrieve data beginning from the specified indexed variable using PHP

I have an array that needs to be searched for specific elements. $map[ ]='A,R,T,E,D,C,B,X,Y'; When searching for a particular element, the function should return 6 elements starting from that element. If the last element is reached, the search ...

What are the steps to incorporate metrics middleware for Socket IO notifications, specifically monitoring both emitted events and listener activity?

I am currently working on a project that involves tracking all socket.io notification transactions initiated by the server, resembling an API request/response counter to validate subscription validation. Our team is utilizing an express middleware to moni ...

Add a new span element to a designated span within the webpage

Original Code: <p class="intro" id="186949"><span class="namepart"><span class="name">john cena</span></span> Desired Code: <p class="intro" id="186949"><span class="namepart"><span class="name">john cena& ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Utilizing Angular Filters to Assign Values to an Object within a Controller

I have a JSON example with multiple records, assuming that each name is unique. I am looking to filter out an object by name in the controller to avoid constant iteration through all the records using ng-repeat in my HTML. { "records": [ { "Name" : ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

What is the best way to compute the total sum of values associated with a specific key in an

Imagine I have an array with multiple objects like so: var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}] My goal is to calculate the sum of all credit values from the arr. The expected sum v ...