简体   繁体   English

优化大块API调用的邮政编码列表

[英]Optimize list of postal codes for API calls in chunks

I'm trying hard to find a good solution to an optimization problem that's pretty difficult for me to solve in the best way using JavaScript. 我正在努力寻找一个优化问题的好的解决方案,这对我来说很难以JavaScript的最佳方式解决。

I've got an array to start with, in which each element is another array containing two postal codes. 我有一个数组开始,其中每个元素是另一个包含两个邮政编码的数组。 I need to calculate the distance between those postal codes using the Google Maps distance matrix API. 我需要使用Google Maps距离矩阵API计算这些邮政编码之间的距离。 The API limits me to 25 "origins" and 25 "destinations" per call, which means I can calculate 625 distances per call. API将我的每次通话限制为25个“原点”和25个“目的地”,这意味着我可以计算每次通话625个距离。 As I've got a huge list of postal codes and only 2500 API calls per day without having to pay for the API usage, I need to optimize those calls the best way possible (+I'm saving the distances locally as a cache). 由于邮递区号清单非常庞大,每天仅需2500次API调用,而无需支付API使用费,因此我需要以最佳方式优化这些调用(+我将距离保存为本地缓存) 。

In code, an example of an array looks like this: 在代码中,数组的示例如下所示:

[[10115, 99734],
[99734, 80331],
[80331, 10115],
[81929, 99734]]

There are no duplicates, so no need to worry about that. 没有重复项,因此无需担心。 At the end, by calling 最后,通过致电

maps.distanceMatrix({
   origins: orArray,
   destinations: destArray
}).asPromise()

I can get the results, but onArray and destArray may only contain 25 postal codes each. 我可以得到结果,但是onArray和destArray可能只包含25个邮政编码。 I can't find a good solution with good runtime-complexity that would work with over 10000 pairs of postal codes. 我找不到具有良好运行时复杂性的良好解决方案,该解决方案可以处理超过10000对邮政编码。

To sum up, I need to "convert" the first array into multiple origin and destination arrays, eg into an array where each element again consists of an origin and destination array on which I just loop over and call the API with. 综上所述,我需要将第一个数组“转换”为多个原始数组和目标数组,例如,转换为每个元素再次由原始数组和目标数组组成的数组,我在其上循环并调用API。 I hope I explained the problem cleary enough. 我希望我已经清楚地解释了这个问题。 It would be awesome if you could give me some ideas on how to solve this the most efficient way as I have been stuck on this for a pretty long time now... 如果您能给我一些有关如何最有效地解决此问题的想法,那将是非常棒的,因为我已经坚持了很长时间了……

Thank you very much! 非常感谢你!

I think you could store these pairs in an object ( hash table ) to optimize: 我认为您可以将这些对存储在对象(哈希表)中以进行优化:

var pairs=[[1,2],[1,3],[4,1]];

var hash={};

pairs.forEach(function(pair){
  if(hash[pair[0]]){
    return hash[pair[0]].push(pair[1]);
  }
  if(hash[pair[1]]){
   return hash[pair[1]].push(pair[0]);
  }
hash[pair[0]]=[pair[1]];
});

Hash should now be: 哈希现在应该是:

{
1:[2,3,4]
}

So you can: 所以你可以:

for(key in hash)
 apiCall({origins:[key],destinations:hash[key]});

Todo: 去做:

{
1:[2,3,4],
5:[2,3,4]
}

could be optimized to: 可以优化为:

{origins:[1,5],destinations:[2,3,4]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM