var element_pairs = [[11.333112,22.655543],[35,31231,33.2232],[122352,343421]];
var search_pair = [32,1113,34.5433];
findClosestPair(element_pairs, search_pair);
// [35,31231,33.2232]
在数组中找到数学上最接近的数字对的最快方法是什么。
答案 0 :(得分:1)
遍历所有元素并切换最短元素并在结尾处返回:
function findClosestPair(elements,search_element) {
var shortestDistance, shortestDistanceIndex;
elements.forEach((el, index) => {
distance = Math.sqrt(Math.pow(el[0] - search_element[0], 2) + Math.pow(el[1] - search_element[0], 2));
if (shortestDistance === undefined || distance < shortestDistance) {
shortestDistance = distance;
shortestDistanceIndex = index;
}
});
return elements[shortestDistanceIndex];
}
你可以在这里看到这项工作=&gt; https://jsfiddle.net/q8738b9a/
答案 1 :(得分:1)
你可以使用Array#reduce
并返回所有对中delta值最小的tupel。
function findClosestPair(elements, search) {
return elements.reduce(function (a, b) {
function getDelta(v, w) {
return Math.abs(v[0] - w[0]) * Math.abs(v[1] - w[1]);
}
return getDelta(a, search) < getDelta(b, search) ? a : b;
});
}
var elements = [[11.333112, 22.655543], [35.31231, 33.2232], [122352, 343421]],
search_element = [32.1113, 34.5433];
console.log(findClosestPair(elements, search_element));
&#13;