2017-10-08 54 views
1
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

你的意思是元素 '对' 但你必须在你的阵列'[35,31231,33.2232]'和'[32,1113,34.5433]' – mseifert

+2

定义“最近的三个要素“ –

+0

测量数字对之间的距离有多种”数学“方法。你想使用哪一个? – Bergi

回答

1

你可以使用Array#reduce,并返回其有三元组所有配对中最小的三角洲。

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));

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]; 
} 

你可以在这里看到这项工作=>https://jsfiddle.net/q8738b9a/

相关问题