Javascript二进制搜索:匹配大于或等于?

时间:2017-01-18 20:05:49

标签: javascript binary-search

此搜索代码返回最接近的匹配项。通常,最接近的match.x小于target.x。

如何返回match.x大于或等于target.x值的最接近匹配,match.y是最接近的y值?

数据按x递增排序,然后按y递增。

var data = [
    {"x": 750, "y": 750},
    {"x": 750, "y": 850},
    {"x": 1000, "y": 500},
    {"x": 1000, "y": 1000},
    {"x": 2000, "y": 2000},
    {"x": 3000,"y": 3000}
];

console.log("Test 800", findClosestMatchGreaterOrEqual({'x': 800,'y': 800}));
// TEST 800 {x: 750, y: 850}

console.log("Test 2300", findClosestMatchGreaterOrEqual({'x': 2300,'y': 2300}));
// TEST 2300 {x: 2000, y: 2000}

function findClosestMatchGreaterOrEqual(target) {
    var low = 0;
    var high = data.length - 1;
    var item = null;
    var lastItem = null;
    while (low <= high) {
        var mid = ((low + high) / 2) | 0;
        lastItem = item;
        item = data[mid];
        var compare = compareItems(item, target);
        if (compare > 0) high = mid - 1;
        else if (compare < 0) low = mid + 1;
        else return item;
    }
    if (Math.abs(lastItem.x - target.x) < Math.abs(item.x - target.x)) return lastItem;
    return item;
}

function compareItems(a, b) {
    if (a.x != b.x) return a.x - b.x;
    if (a.y != b.y) return a.y - b.y;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

根据语句closest match where match.x is greater or equal to target.x value and match.y is the closest y value,我尝试更改您的功能,如下所示,它将为您提供所需的输出。

&#13;
&#13;
var data = [
    {"x": 750, "y": 750},
    {"x": 750, "y": 850},
    {"x": 1000, "y": 500},
    {"x": 1000, "y": 1000},
    {"x": 2000, "y": 2000},
    {"x": 3000,"y": 3000}
];

function closest(target) {
	var arr = [],result;
	for (var i=0; i<data.length; i++) {
		arr.push({index: i, diffy: Math.abs(target.y - 	data[i].y),diffx: Math.abs(target.x - 	data[i].x), x:data[i].x,  y: data[i].y});
  }
  arr = arr.sort(function(a, b) {
    return parseFloat(a.diffy) - parseFloat(b.diffy);
	});
  
  for (var i=0; i<arr.length; i++) {
		if(arr[i].x >= target.x) {
    		result = arr[i];
        break;
    }
  }
  console.log(arr);
  console.log(data[result.index]);
  alert(JSON.stringify(data[result.index]));
}

closest({"x": 1000, "y": 1600});
&#13;
&#13;
&#13;