计算通过三个数组的最短路径 [英] Compute the shortest path going through three arrays
本文介绍了计算通过三个数组的最短路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个数组,也可能是n。我们现在就拿三个。
它们的值如下: -
I have three arrays or it may be n. let us take three now. They have values like these:-
Array1=[143, 181];
Array2=[41, 153, 241];
Array3=[22, 67, 131, 190];
我想找到这三个数组的元素,谁有最小的差异。
在这种情况下,143,153,131具有最小差异。
I want to find those elements of these three array, Who has minimum difference. Like in this case 143,153,131 has minimum difference.
推荐答案
假设您没有大量数组,这是一个解决方案,计算(和存储)所有路径:
Assuming you don't have a big number of arrays, here's a solution, computing (and storing) all paths:
// First let's use a sensible structure
var arrays = [Array1, Array2, Array3];
// Then, let's compute all possible paths
var paths = arrays[0].map(function(v){ return [v] });
for (var i = 1; i<arrays.length; i++) {
var arr = arrays[i];
for (var j=paths.length; j--; ) {
var newPaths = arr.map(function(v){
return paths[j].concat(v);
})
newPaths.unshift(j,1);
[].splice.apply(paths, newPaths);
}
}
// Now, let's just take the shortest one
var shortestDistance = Infinity,
shortestPath = null;
paths.forEach(function(path){
var distance = 0;
for (var i=1; i<path.length; i++) {
distance += Math.abs(path[i]-path[i-1]);
}
if (distance<shortestDistance) {
shortestDistance = distance;
shortestPath = path;
}
});
// Finally, let's log the result
console.log(shortestDistance, shortestPath);
它记录
32
[143, 153, 131]
这篇关于计算通过三个数组的最短路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文