我目前正在使用Google DistanceMatrix获取多个点之间的距离。
例如,我有4个不同的点,为了得到每个点之间的距离,我给出4个点作为起点和目的地。
"destination_addresses" : [
"201 W 75th St, New York, NY 10023, USA",
"569-573 Columbus Ave, New York, NY 10024, USA",
"142a E 79th St, New York, NY 10075, USA",
"1350-1352 Madison Ave, New York, NY 10128, USA"
],
"origin_addresses" : [
"201 W 75th St, New York, NY 10023, USA",
"569-573 Columbus Ave, New York, NY 10024, USA",
"142a E 79th St, New York, NY 10075, USA",
"30 E 95th St, New York, NY 10128, USA"
],
...
这给了我一个4 x 4阵列,这是有道理的。但现在我想找到从A
到B, C and D
的所有可能路线。
所以基本上我想找到并获得总距离和持续时间
A -> B -> C -> D
A -> B -> D -> C
A -> C -> B -> D
...
我尝试编写一个递归函数,但失败了。最好的方法是什么?
答案 0 :(得分:0)
这是固定长度路线的解决方案。这基本上是使用递归函数来生成数组的所有排列(另请参阅Generate permutations of JavaScript array)
var destination_addresses = [
"201 W 75th St, New York, NY 10023, USA",
"569-573 Columbus Ave, New York, NY 10024, USA",
"142a E 79th St, New York, NY 10075, USA",
"1350-1352 Madison Ave, New York, NY 10128, USA"
],
origin_addresses = [
"201 W 75th St, New York, NY 10023, USA",
"569-573 Columbus Ave, New York, NY 10024, USA",
"142a E 79th St, New York, NY 10075, USA",
"30 E 95th St, New York, NY 10128, USA"
];
function permutate(arr) {
if (arr.length < 2) return arr;
var permutations = [];
for (var i = 0; i < arr.length; i++) {
var restArr = arr.slice(0, i).concat(arr.slice(i + 1, arr.length));
for (var subPermutation of permutate(restArr))
permutations.push([arr[i]].concat(subPermutation))
}
return permutations;
};
console.log(JSON.stringify(permutate([1, 2, 3])));
&#13;
我使用了数组[1, 2, 3]
,但您可以将其替换为destination_addresses
。
如果您正在寻找最短的路线,那么就是旅行商问题的一个案例,您将需要使用一些近似算法来寻找可行的解决方案。