この検索コードは、最も近い一致を返します。多くの場合、最も近いmatch.xはtarget.xより小さい。Javascriptバイナリ検索:より大きいか等しいだけで一致しますか?
match.xがtarget.x値以上で、match.yが最も近いy値である場合、どのようにして最も近い一致を返すことができますか?
データはxで昇順にソートされ、yで昇順にソートされます。声明closest match where match.x is greater or equal to target.x value and match.y is the closest y value
に基づいて
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;
}
あなたはこれを自分で書き換えしようとしたのですか?もしそうなら、何を試しましたか? – andi
function compareItems(a、b){ if(a.x!= b.x && a.x
Sparky1