从位置列表构建距离矩阵
我有一个文本文件,里面列出了不同的城市和它们的具体经纬度值。还有一段代码可以根据一个起点和一个终点,利用 Google maps API
计算这两点之间的距离。现在我遇到的问题是,如何构建一个距离矩阵,像这样:
x loc1 loc2 loc3 ...
loc1 [0 3 4]
loc2 [5 0 7]
loc3 [9 2 0]
....
而这个文本文件的内容是这样的:
location1, lat1, long1
location2 lat2, long2
location3, lat3, long3
有没有什么建议可以帮我解决这个问题?我觉得我把事情搞得比实际复杂了。我想过用一个循环,先取第一个位置,然后遍历所有其他位置,再把第一行加到最后,然后再回到开头。这样做是基于我知道文本文件里有多少行,这样也没问题,但最后得到的数组可能会很麻烦,需要重新整理。
1 个回答
0
这是我一直在找的答案,顺便告诉大家一下。
xxxxxxxxxxxxxxxxxx 答案:
你有一个包含多个邮政编码的列表,记作zip(n),其中n的范围是1到N。
每个zip(n)都有一个纬度值和一个经度值,比如zip(n).lat = 44.22;zip(n).long = 39.17。
那么,距离的矩阵就会是M(N,N)——这是一个方阵,对角线上的值总是0,因为一个邮政编码到它自己之间的距离是0。此外,矩阵的上半部分和下半部分是一样的。这意味着从zip1到zipX的距离和从zipX到zip1的距离是相同的。因此,你只需要计算矩阵的一半,排除对角线的部分。这样做也可以作为一个错误检查。
他的代码有点乱,而且不是用Python写的,但逻辑过程是一样的,这正是我卡住的地方。如果大家感兴趣,我把他的代码贴在下面(是用Java写的)。
循环的部分是:
Map<int,int> M = new HashMap<int,int>(); - in Java all values are initialized to 0 for you; index goes from 0...N-1
for (int r = 1; r < N-1; r++) { // Skip the two corners (0,0) and (N-1,N-1) which are 0
for (int c = r + 1; c < N; c++) {
M(r,c) = getDistance(zip(r),zip(c));
}; // end for c
}; // end for r
You can also use an Map of Integers where the key is the string r+","+c
Map<String,Integer> M = new HashMap<String,Integer>();
for (int r = 1; r < N-1; r++) { // Skip the two corners (0,0) and (N-1,N-1) which are 0
M.put(r+","+r,new Integer(0)); // diagonal
for (int c = r + 1; c < N; c++) {
M.put(r+","+c,new Integer(getDistance(zip(r),zip(c))); // Upper half
M.put(c+","+r,new Integer(getDistance(zip(r),zip(c))); // Lower half
}; // end for c
}; // end for r
M.put("0,0",new Integer(0)); // upper left corner
M.put((N-1)+","+(N-1),new Integer(0)); // lower right corner