计算一系列许多斜坡

时间:2016-08-30 01:13:03

标签: java time-complexity big-o

我有一个坐标列表,我目前有一个功能处理所述坐标以找到斜率,所有顺序和配对

public void foo(){

    int[] xCoords = {//stuff}
    int[] yCoords = {//stuff}

    for(int i = 0; i < 100000; i++){
        getSlope(x[i], y[i], xcoords, ycoords)
    }
}

public int getSlope(int x, int y, int[] x1, int[] y1){
    //calculate slope using m = (y - y1) / (x - x1);
    double slope;
    for(int i = 0; i < x1.length(); i++){
        slope = (y - y1[i]) / (x - x1[i]); 
        return slope;
    }
    return -2;
}

这一切都很好,但我想知道如何用大量的坐标来做到这一点。从另一个放置要评估的坐标的方法调用getSlope,这个运行速度非常慢O(n ^ 2)我认为(for循环中的循环)。

有更快的方法吗?

完全披露:这是一个更大的学校作业的一部分,所以我不喜欢答案只是与时间复杂性和大哦相关的想法。

编辑:进一步澄清。 编辑2:进一步澄清。

1 个答案:

答案 0 :(得分:0)

假设您想要找到坐标数组中两个连续点之间的斜率:

public void foo(){

    int[] xCoords = {//stuff}
    int[] yCoords = {//stuff}

    double slope;
    for(int i = 0; i < xCoords.length-1 && i < yCoords.length-1; i++){
        slope = getSlope(xCoords[i], yCoords[i], xCoords[i+1], yCoords[i+1]);
        System.out.println(slope);
    }
}

public double getSlope(int x, int y, int x1, int y1){
    //calculate slope using m = (y - y1) / (x - x1);
    return (y - y1) / (x - x1);
}

修改 如果你想要的是相对于固定参考点有多个斜率,你的方法应该返回多个值,如下所示,但如果你想从你的方法返回一个斜率,那么就不需要循环和你的方法不需要将数组作为参数;您可以只传递两对坐标进行单一斜率计算。

public void foo(){

    int[] xCoords;// = {//stuff}
    int[] yCoords;// = {//stuff}

    int referenceX = //set to your value
    int referenceY = //set to your value
    double[] slopes = getSlope(referenceX, referenceY, xCoords, yCoords)
}

public double[] getSlope(int x, int y, int[] x1, int[] y1){
    //calculate slope using m = (y - y1) / (x - x1);
    double[] slope = new double[(x1.length<y1.length)? x1.length:y1.length];
    for(int i = 0; i < x1.length && i < y1.length; i++){
        slope[i] = (y - y1[i]) / (x - x1[i]); 
    }
    return slope;
}