-1

we have some ranges of frequency in a 2D array. the inner arrays keep frequency upper and lower bounds ,and outer array is a list of sorted ranges:

/*
[
[L0,U0],
[L1,U1],
[L2,U2]
]
*/

let freqList = [
[272.50,275.86],
[279.18,283.34],
[288.78,293.12]
]

new ranges should not overlap saved ones, how can i validate new ones and push them to exact array index?

  • Check each entry if it's first member is larger than the last member of the previous entry. Perhaps it makes more sense to see how you're pushing data into `freqList`: see how to create a [mcve] – Terry Jan 27 '22 at 20:43
  • thank you @Terry , this is my first question on Stackoverflow, sorry for that. –  Jan 27 '22 at 20:50

1 Answers1

1

I think you just need to find the first index such that it's lower number is greater than your lower number. Make sure that your greater number is also lower than it's lower number. Make sure the previous elements greater number is less than your lower number. Then slice it into that index:

let freqList = [
    [272.50,275.86],
    [279.18,283.34],
    [288.78,293.12]
]

const addRange = (min, max) => {
    if (min > max) {
    throw new Error('invalid')
    }
    // find the first element where the min element is greater than the current min
    // this could be a binary search if you need to care about performance
    const i = freqList.findIndex(el => el[0] >= min);
    if (i === -1) {
        freqList.push([min, max]);
    }
    if (max >= freqList[i][0] || (i !== 0 && min < freqList[i-1][1])) {
        throw new Error('invalid')
    }
    freqList.splice(i, 0, [min, max]);
}

addRange(100, 200)
console.log('ok')
try {
    addRange(0, 101);
} catch(e) {
    console.log('invalid range caught')
}
try {
    addRange(199, 201);
} catch(e) {
    console.log('invalid range caught')
}
dave
  • 62,300
  • 5
  • 72
  • 93