估计给定参数值增加的平均时间

时间:2014-12-29 13:19:59

标签: java

有以下数组track表示某些参数的增加。每行指的是5天:

[0] 5
[1] 10
[2] 12
[3] 11
[4] 7
[5] 6
[6] 10
[7] 15
[8] 16

我需要估算参数增加的平均时间。在这个例子中,从[0]到[2],从[5]到[8]。答案必须是:

Period 1 (from [0] to [2]) = 5+5+5 = 15 days. 
Period 2 (from [5] to [8]) = 20 days 
ANSWER = (15 + 20)/2 = 17.5 days

我写了以下代码。但它失败了因为curr是>比最后一次迭代的track.length。我该如何解决这个问题?

    private double getAvgGrowingTime(double[] track)
    {
        List<Double> timeList = new ArrayList<Double>();

        double temptime = 0.0;
        boolean stop = false;
        int curr = 1;
        while (curr < track.length)
        {
            while (track[curr]>track[curr-1])
            {
                temptime += 5;
                stop = false;
                curr++;
            }
            if (!stop)
                timeList.add(temptime);
            temptime = 0.0;
            stop = true;
            curr++;
        }

//...

    }

2 个答案:

答案 0 :(得分:1)

将内心改为:

while ( curr< track.length && track[curr]>track[curr-1])
{
     temptime += 5;
     stop = false;
     curr++;
}

答案 1 :(得分:1)

两个问题:

  • 当你有5,10,15这样的数据时,你的输出将是10,你需要15。
  • 您将使用上面的示例运行ArrayIndexOutOfBoundException,因为它将进入您的内部while循环,并且不会检查当前索引中的元素数量。

要解决您的两个问题,您可以执行以下操作:

boolean first = true;
while (curr < track.length) {
    while (curr < track.length && track[curr] > track[curr - 1]) {
         if (curr == 1 && first) {
             temptime += 5;
             first = false;
         }