Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array replace with close range Javascript

Let's say we have a List of ranges expressed in arrays with two elements [from, to].

When we add a new array range like [5,8], it should check in List if there is a closest range and then replace it with the new range value. An example is provided below:

Example 1

var List = [[1,2], [3,4], [6,7], [9,10]]

var newData = [5,8]

Expected Output:

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

The [6,7] range is already included in [5,8]

Example 2

var List = [[1,3], [4,6], [8,10]]
var newData = [5,9]

Expected Output:

[[1,3], [4,10]]
like image 789
Alexey Avatar asked Aug 31 '26 02:08

Alexey


1 Answers

Assuming the initial list is well-formed, with its pairs sorted and non-overlapping, you could use binary search to find the end points of a new pair in the array and so determine any overlap. If overlap, splice the array accordingly:

function addSegments(segments, ...pairs) {
    for (let pair of pairs) {
        let [start, end] = pair.map(function (x, i) { // Binary search
            let low = 0, 
                high = segments.length;
                side = 1 - i;
            while (low < high) {
                let mid = (low + high) >> 1;
                if (x < segments[mid][side]) high = mid;
                else low = mid + 1;
            }
            return low - (side && segments[low-1]?.[side] === x);
        });
        if (start < end) {
            pair = [
                Math.min(segments[start][0], pair[0]),
                Math.max(segments[end-1][1], pair[1])
            ];
        }
        segments.splice(start, end - start, pair);
    }
}

// Demo
let list = [[1, 2], [3, 4], [6, 7], [9, 10]];
addSegments(list, [5, 8]);
console.log(JSON.stringify(list));

list = [[1, 3], [4, 6], [8, 10]];
addSegments(list, [5, 9]);
console.log(JSON.stringify(list));
like image 51
trincot Avatar answered Sep 01 '26 15:09

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!