我正在修改編程考試簡介,並且我有一個問題,從之前的考試論文中我略微停留。爲火車線路上的所有車站創建一個距離圖
問題:
收件採用一個雙陣列與表示車站的沿軌道的位置的值的參數的方法。該方法應返回一個二維數組,其中參數中每對站之間的距離。距離陣列對於每一對站點應該只有一個入口(即不使用矩形陣列)。
我有一個問題的解決方案,但我不能得到最後一點,應該只有一個條目每對。我曾想過創建一個查找表將所有條目查看兩個工作站的距離是多少,然後這個數組會有很多空閒單元用於較晚的工作站,因爲距離已經被計算出來了。
這是我目前的解決方案
//Set of locations on the train line
private static double[] stations = {0.0, 2.0, 3.0, 5.0};
//Method to take the array of doubles and create distance map
public static double[][] getDistances(double[] st){
double[][] distanceMap = new double[st.length][st.length-1];
int x;
for(int i=0; i<st.length; i++){
x=0;
for(int j=0; j<st.length; j++){
if(j != i){
distanceMap[i][x] = Math.abs(st[i]-st[j]);
x++;
}
}
}
return distanceMap;
}
//Main method to get the distance map then loop over results
public static void main(String[] args){
double[][] arrayMatrix = getDistances(stations);
for(int i=0; i<arrayMatrix.length; i++){
for(int j=0; j<arrayMatrix[0].length; j++){
System.out.print(arrayMatrix[i][j]+" ");
}
System.out.println("");
}
}
如果任何人都可以在正確的方向點我將非常感激。
在此先感謝。
//編輯
後從@izomorphius一些很好的建議,我已成功地解決了這個問題。謝謝。
下面是完整的解決方案
//Set of locations on the train line
private static double[] stations = {0.0, 2.0, 3.0, 5.0};
//Method to take the array of doubles and create distance map
public static double[][] getDistances(double[] st){
double[][] distanceMap = new double[st.length-1][];
int size = st.length-1;
for(int i=0; i<distanceMap.length; i++){
distanceMap[i] = new double[size];
size--;
}
ArrayList<String> lut = new ArrayList<String>();
int x;
for(int i=0; i<distanceMap.length; i++){
x=0;
for(int j=0; j<st.length; j++){
if(j != i && !lut.contains(i+"/"+j)){
distanceMap[i][x] = Math.abs(st[i]-st[j]);
lut.add(i+"/"+j);
lut.add(j+"/"+i);
x++;
}
}
}
return distanceMap;
}
//Main method to get the distance map then loop over results
public static void main(String[] args){
double[][] arrayMatrix = getDistances(stations);
for(int i=0; i<arrayMatrix.length; i++){
for(int j=0; j<arrayMatrix[i].length; j++){
System.out.print(arrayMatrix[i][j]+" ");
}
System.out.println("");
}
}
+1 @TrueWheel,我認爲這個請求的目的是看你如何處理動態分配數組 – giorashc
謝謝!我從來沒有意識到你可以創建一個三角陣列。我在問題的底部添加了我的解決方案。 – TrueWheel