Discovering pairs of numbers that are not next to each other in an array that has not been

When working with an array of unsorted numbers, the goal is to identify and extract pairs of elements that are not consecutive.

Input [2,3,4,5,9,8,10,13]
Desired output (2,5)(8,10)(13,13)

To achieve this:

Input = [2,3,4,5,9,8,10,13]

If we arrange the numbers in increasing order, we get:

[2,3,4,5,8,9,10,13]

We then break down the sequence where the continuity breaks:

[2,3,4,5]
[8,9,10]
[13]

The output will consist of the first and last number in each group. If a group has only one number, it will be treated as both the first and last.

Output:

[2,5][8,10][13,13]

This can be achieved using the following JavaScript code:

var array = [2,3,4,5,9,8,10,13];
var input = array.sort((a,b)=>{return a-b});
var group = [];
var start = input[0];
for(let i = 0; i<input.length; i++){
    if(input[i+1] - input[i] > 1){
        group.push([start,input[i]]);
        start = input[i+1];
    }
}
console.log(group);

The resulting output from the code would be:

[ [ 2, 5 ], [ 8, 10 ] ]

Answer №1

My Unique Method

Here is a fresh implementation that follows the steps outlined above. Initially, we perform a numeric sorting. Subsequently, utilizing reduce, we segment the numbers into consecutive groups. Finally, we utilize map to extract the first and last values from each array.

To streamline the process, we introduce a straightforward helper function called last which retrieves the final element of an array.

const last = (xs) => 
  xs [xs .length - 1]

const nonConsecutives = (ns) =>
  [...ns] 
    .sort ((a, b) => a - b) 
    .reduce (
      (r, n, i) => (i == 0 || n > last (last (r)) + 1)
        ? r .concat ([[n]])
        : r .slice (0, -1) .concat ([last (r) .concat (n)]),
      []
    ) 
    .map (ns => [ns [0], last (ns)])


console .log (
  nonConsecutives ([2, 3, 4, 5, 9, 8, 10, 13])
)

Revised Approach

If you are wondering about the flaws in your approach, it mainly lies at the boundaries. The line

if (input [i + 1] - input [i] > 1)
encounters issues at the last index since there is no input [i + 1]. Similarly, updating start = input [i + 1] during the initial iteration should be avoided.

A more effective version address these concerns by testing between the current and previous indices. An additional pre-check ensures accuracy even though it may seem redundant. Following the loop, a final group is pushed for completion.

Check out this implementation:

const array = [2, 3, 4, 5, 9, 8, 10, 13]
const input = array .sort ((a, b) => a - b)
const group = []
let start = input [0]
for (let i = 0; i < input .length; i++){
    if (i == 0 || input [i] - input [i - 1] > 1) {
        if  (i > 0) {
          group .push ([start, input [i - 1]])
        }
        start = input [i]
    }
}
group .push ([start, input [input .length - 1]])

console.log(group);

Divergence in Strategies

The disparity between the two approaches is quite significant. One notable variance is my encapsulation within a function, following a functional programming paradigm. Moreover, I employ distinct transformations such as sorting, grouping, and capturing endpoints explicitly to enhance clarity. Although this may sacrifice efficiency, it prioritizes transparency.

Furthermore, a crucial differentiator is the absence of variable mutations in my version. Embracing immutable data transformation aligns with core principles of functional programming.

Exploring Ramda

As a co-founder of the Ramda functional programming library, I gravitate towards its streamlined approach to problem-solving. By leveraging tailored functions without altering the data state, Ramda promotes clean code structure. A simplified rendition using Ramda might look like this:

const {pipe, sortBy, identity, groupWith, map, juxt, head, last} = R

const nonConsecutives = pipe (
  sortBy (identity),
  groupWith ((a, b) => b - a <= 1),
  map (juxt ([head, last]))
)

console .log (
  nonConsecutives ([2, 3, 4, 5, 9, 8, 10, 13])
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>

Delving into the intricacies of this method exceeds the scope here. Regardless, embracing smaller, pure functions can pave the way for efficient functional programming practices.

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

An error occurred when attempting to use the getDoc() function from Firebase within Next.js: TypeError - reading 'map' on properties of undefined

Hello everyone at StackOverflow, I ran into a problem while attempting to use .map() on a getDoc() constant in my Next.js application. The error message I'm getting is: "TypeError: Cannot read properties of undefined (reading 'map')". As a n ...

Ways to randomize an array without any repeating elements with the help of jQuery?

let numbers = [5, 12, 18, 23, 30]; What is the most efficient way to randomize the order of these numbers in a new array without any duplicates? Example: newArr = [18, 30, 5, 12, 23]; ...

Concatenating an unlimited amount of arrays containing Javascript objects

I currently have an array of Groups where each Group contains multiple Users. My goal is to retrieve all the unique Users associated with a given array of Groups. Here is my current approach: let actor = await User.query().findById(req.user.id).eager( ...

How to Add Elements to a JSON Array using Scrapy

Currently, I am utilizing the Python framework Scrapy to scrape websites and save the collected data into a JSON array. The command I use to store the data is as follows: scrapy crawl dmoz -o items.json -t json Whenever I run this command, it generates a ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

What steps can be taken to prevent users from dragging a page horizontally?

One function on my site involves a horizontal scroll that animates the DIV to the left when a button is clicked. The element's width is set at 18000px, ensuring it has a horizontal scrollbar that I have since disabled. Despite this, users are still ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

Sending PHP output data to jQuery

Trying to implement this code snippet /* Popup for notifications */ $(document).ready(function() { var $dialog = $('<div></div>') .html('message to be displayed') .dialog({ ...

Inspect the properties of a ReactJS component using Playwright

I'm relatively new to end-to-end (E2E) testing. One area I am looking to test involves changing the shipping address and automatically setting it as the billing address. For example, if I input Grove Street as my shipping address, I want it to mirror ...

Having trouble getting a form to submit to a Rails server using AJAX in IE11 with jQuery

Currently, I'm attempting to transfer data from a form to a Rails server using AJAX. The form consists of two text inputs and one file input. Below is the code for my submit event handler: $("form").on("submit", function(event) { event.preventDefa ...

Generate a JSON array containing objects consisting of a combination of string and boolean values

My goal is to generate a list containing objects with names and boolean values by utilizing AJAX. This process is initiated in the following manner: $('.si-accordion').click(function () { $(this).siblings('.accordion_tab&apo ...

Is there a way to emphasize text within a string of object array items?

I am currently utilizing the data provided below to pass as props in React. The functionality is working smoothly, but I have a specific requirement to only emphasize the words "target audience" within the text property. Is there a feasible way to achieve ...

Is there a way to incorporate a variable into a JSON URL?

I'm attempting to incorporate a variable I have defined into the JSON URL: var articleName = "test"; $.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType= ...

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...

Submitting with enter key on typeahead suggestions

Seeking guidance on Bootstrap typeahead: how can I configure it to submit the entered text upon pressing the enter key? Specifically, if I type "hello" in the typeahead input and hit enter, how can I submit "hello"? I've successfully disabled the aut ...

Responsive Website with Horizontal Scrolling

Is it feasible to develop a website that smoothly scrolls across five panels horizontally while maintaining responsiveness? I've managed to achieve this for a specific viewport size by nesting a div with the five panels extended and using javascript t ...

What is causing the javascript in my svg files not to function when embedded in an html document?

I have the following code for an SVG: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="470px" height="260px" version="1.1" onload="addEvent ...

Node.js and Express experiencing issues with updating cookies functionality

After successfully logging in, I created a login cookie. However, when I attempted to update the data within that cookie, an error occurred: Can't set headers after they are sent. Below is the code snippet in question: /* Logout to main user. */ /* ...

Enhancing AngularJS functionality through the integration of jQuery within a TypeScript module

As I try to integrate TypeScript into my codebase, a challenge arises. It seems that when loading jQuery and AngularJS in sequence, AngularJS can inherit functionalities from jQuery. However, when locally importing them in a module, AngularJS fails to exte ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...