简体   繁体   中英

indexes around a range of values

Considering a sorted array arr

1- Simple case:

var arr = [3, 6, 12, 18];
indexesAround(6)
//> [1, 1]
indexesAround(7)
//> [1, 2]

2- More complex case:

var arr = [3, 3, 6, 6, 18, 18];
indexesAround(6)
//> [2, 3]
indexesAround(7)
//> [3, 4]

How would you implement(or pseudo code) a such indexesAround(value) function ?

--

Here is what I have for now, but I think this could be enhanced:

function indexesAround(val) {
  var lower = 0;
  var upper = lower;

  var el;
  for (var i = 0, len = arr.length; i < len; i++) {
    el = arr[i];

    if (el > val) {break;}
    if (arr[lower] < el) {lower = upper = i;}
    if (arr[upper] <= el) {upper = i;}
  }

  return [lower, upper];
}

This solution covers every possibility and works exactly to OP's specifications. Run it on jsfiddle .

Code

function indexesAround(target,array) {
    var start;
    var len = array.length;

    for(i = 0; i < len; i++) {
        if (array[i] == target && !start) { start = i; }
        if (array[i] > target) {
            if(i == 0) { return [ 0, 0 ]; }   // Target lower than array range
            if(!start) { return [ i-1, i ]; } // Target inside array range but not found
            return [ start, i-1 ];            // Target found
        }
    }

    if(start) { return [ len-1, len-1 ]; } // Target higher than array range
    return [ start, len-1 ];               // Target found and extends until end of array
}

Considering the array is sorted:

function indexesAround(arr, val) {
  if (!~arr.indexOf(val)) return false; // not found
  var start = arr.indexOf(val);
  var end = (arr.length - 1) - arr.reverse().indexOf(val);
  arr.reverse(); // restore original order
  return [start, end];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM