How can I detect breaks in intervals?

Consider the following ranges as examples:

const ranges = [
  [
    0,
    10,
  ],
  [
    20,
    30,
  ],
  [
    40,
    50,
  ],
];

In this scenario, I am looking to identify the missing ranges between two given values. For instance, if the input range was [-10, 60], the expected output should be as follows:

const islands = [
  [
    -10,
    -1,
  ],
  [
    11,
    19,
  ],
  [
    31,
    39,
  ],
  [
    51,
    60,
  ],
];

I attempted to search for terms like "disjoint ranges" and "non-intersecting ranges" but did not come across a solution. It seems like a common problem that may have been addressed numerous times in the past. Perhaps I am using incorrect search terms.

Answer №1

When it comes to searching for intersections within intervals, one of the primary data structures you can rely on is the Interval Tree. By creating an interval tree based on ranges, you can easily identify intersections between the input range and the tree through queries. Then, a sweep from left to right of the input range can help pinpoint any gaps.

For those looking to implement an interval tree in JavaScript, there are a variety of options available, such as the one provided in this repository.

Answer №2

function findMissingNumbers(arr, ranges) {
  let [min, max] = arr;
  return ranges.reduce((acc, range, index) => {
    if (range[0] < min) return acc;
    if (min < range[0]) acc.push([min, range[0] - 1]);
    if (index === ranges.length - 1 && max > range[1]) acc.push([range[1] + 1, max]);
    min = range[1] + 1;
    return acc;
  }, []);
}

let ranges = [ [2, 10], [5, 7], [40, 50] ];
console.log(findMissingNumbers([-10, 60], ranges));

ranges = [ [0, 10],[20, 30],[40, 50]];
console.log(findMissingNumbers([-10, 60], ranges));

Answer №3

I successfully implemented a solution that accounts for all possible edge cases that crossed my mind.

I wanted to share this code in case nobody else comes up with a more efficient solution:

function identifyGaps(rangesList) {
  const gapsList = [];

  for (let i = 0; i < rangesList.length - 1; i++) {
    const startRange = rangesList[i][1];
    const endRange = rangesList[i + 1] ? rangesList[i + 1][0] : null;

    if (startRange < endRange) {
      gapsList.push([startRange + 1, endRange - 1]);
    }
  }

  return gapsList;
}

function findMissingRanges(rangesList, fromNum, toNum) {
  if (rangesList.length === 0) {
    return [[fromNum, toNum]];
  }

  const gapsList = [
    [Number.NEGATIVE_INFINITY, rangesList[0][0] - 1],
    ...identifyGaps(rangesList),
    [rangesList[rangesList.length - 1][1] + 1, Number.POSITIVE_INFINITY],
  ];

  return gapsList
    .filter((gap) => {
      return isRangeOverlapping(gap, [fromNum, toNum]);
    })
    .map((gap) => {
      return [Math.max(gap[0], fromNum), Math.min(gap[1], toNum)];
    });
}

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

Having trouble with publishing to npm as public with the --access flag not functioning properly?

When trying to publish a fresh scoped package on NPM using the command npm publish --access public, I encountered the following error: ole@mki:~/cli$ npm publish --access public npm ERR! publish Failed PUT 403 npm ERR! code E403 npm ERR! F ...

Leverage the power of AJAX for fetching data from a database in Node.js

As I am utilizing Node.js as the server and Mysql as the database to store logged in usernames, I am curious if it is possible to use AJAX to execute a SQL database query and retrieve a list of usernames. More precisely, I am interested in using XMLHttp r ...

"Exploring the differences between request.body, request.params, and request.query

I am working with a client-side JS file that includes: agent = require('superagent'); request = agent.get(url); Afterwards, the code looks something like this: request.get(url) //or request.post(url) request.end( function( err, results ) { ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

transforming JSON into CSV structure

I am attempting to utilize a JSON file as input data. Below is an excerpt of sample data. [ { id: 1671349531, name: "A Wild Restaurant Expansion", blurb: "We are looking to expand from our current location to a new and better facility...", goal: 17000, pl ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

The execution of JQuery/Javascript is restricted to only the initial condition within a Visualforce page utilizing the apex:outputpanel tag

After using only JavaScript for some time, I decided to try out jQuery. However, I'm facing an issue with executing a jQuery function. It seems that only the first condition in my code (the first IF) is being executed, while the second one (the second ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

Introducing the new default in Google Chrome: Now accessing window.opener for target="_blank" links after rel="noopener" is the standard feature

Exploring a new attribute called rel="noopener", I discovered that it keeps opened windows unaware of their opener. After some experimentation, I consistently found window.opener === null, only to realize that this is now the default behavior in ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

Double execution of code in Swift to validate and store data

After completing a substantial block of code, I've noticed that it runs twice whenever the method containing the code is called. While I can't share the entire complex code due to its sensitive data, I can provide an explanation regarding its str ...

Error in Javascript programming | tracking progress bar

After stumbling upon this code snippet at this link, I was eager to delve deeper into the world of JavaScript and jQuery. However, upon implementing these codes, I encountered a perplexing issue. The progress bar and continue buttons seem to be non-funct ...

What is the best way to initialize firebase with context in a React application?

Currently, I'm following a tutorial at this link: I've hit a roadblock at the following step: Context.jsx import React from 'react'; const FirebaseContext = React.createContext(null); export default FirebaseContext; index.js impo ...

Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website. The main text in the center needs to change every 60 seconds. I have over 150 individual lines of text that I want to cycle through on the page. What would be the most efficient way to load all these te ...

Convert former function to use async and await system

I need to convert this function to async, but I am facing an issue where the users object obtained from mapping interactions is not returning data in the expected format. When I run the async function on the client side, my values are showing up as nil. Th ...

Transfer data from a child component to a parent component in a React application

Currently, I am working on my second React app. This time, I am experimenting with nested components, unlike my previous project which only had a single component. The main focus of this project is a calculator app built using React. To guide my design pro ...

Creating duplicates of an array by dereferencing pointers

I'm currently working on transferring values from one array to another (specifically values 200 - 299) while dereferencing pointers. *ptr = &arr2[100]; //points to position 100 in array2, which contains numbers 100-300 Instead of directly copyi ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

Personalized FullCalendar header title

Is there a way to display a unique header title for each calendar in my collection of 16? I've been trying various modifications to the code snippet below with no success: firstDay: <?php echo $iFirstDay; ?>, header: { left: 'prev,next ...

Tips for enabling item draggability following AJAX filtering operations

I have a draggable list of names that can be filtered using checkboxes. When a checkbox is checked, an ajax call is made to filter the names. The list is displayed in an accordion format as shown below: <div id="myAccordion"> <?ph ...