2012-05-10 30 views
1

我正在修改編程考試簡介,並且我有一個問題,從之前的考試論文中我略微停留。爲火車線路上的所有車站創建一個距離圖

問題:

收件採用一個雙陣列與表示車站的沿軌道的位置的值的參數的方法。該方法應返回一個二維數組,其中參數中每對站之間的距離。距離陣列對於每一對站點應該只有一個入口(即不使用矩形陣列)。

我有一個問題的解決方案,但我不能得到最後一點,應該只有一個條目每對。我曾想過創建一個查找表將所有條目查看兩個工作站的距離是多少,然後這個數組會有很多空閒單元用於較晚的工作站,因爲距離已經被計算出來了。

這是我目前的解決方案

//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(""); 
    } 

} 

回答

2

什麼聲明說,是的「即不使用矩形陣列」。這個想法是隻爲每一對存儲一個值。例如,如果你有一對(a,b),並且一個< b存儲a和b之間的距離,但是不在b的一箇中。因此,第一站的陣列大小爲n-1(到所有其他站的距離),第二站的大小爲n-2(除了第一站之外的所有其他站)等等。因此你的陣列將是三角形而不是矩形。我希望這個提示已經足夠了,因爲畢竟這個想法並不是讓我解決你的問題。

+0

+1 @TrueWheel,我認爲這個請求的目的是看你如何處理動態分配數組 – giorashc

+0

謝謝!我從來沒有意識到你可以創建一個三角陣列。我在問題的底部添加了我的解決方案。 – TrueWheel