有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为火车线上的所有车站创建距离地图

我正在复习程序设计入门考试,我有一道题,来自上一篇试卷,我有点被卡住了

问题是:

Write a method that takes a double array as an argument with values representing the positions of train stations along a track. The method should return a two-dimensional array with the distances between each pair of stations in the argument. The array of distances should have only one entry for each pair of stations (i.e. do not use a rectangular array).

我对这个问题有一个解决方案,但我就是无法得到最后一点,即每一对应该只有一个条目。我曾考虑过创建一个查找表来查找所有条目,以查看两个站点的距离是否相同,但由于距离已经计算出来,因此阵列中会有很多空单元用于后面的站点

这是我目前的解决方案

//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) 个答案

  1. # 1 楼答案

    声明中说的是“即不要使用矩形阵列”。这样做的目的是为每一对存储一个值。例如,如果你有一对(a,b)和a<;b将a和b之间的距离存储在a的数组中,但不存储在b的数组中。因此,第一个站的数组大小为n-1(到所有其他站的距离),第二个站的数组大小为n-2(除第一个站外的所有其他站),依此类推。因此,您的阵列将是三角形而不是矩形。我希望这个建议足够了,毕竟我的想法不是让我解决你的问题