声明分析两种不同的算法

时间:2013-07-29 19:07:29

标签: java time-complexity

我最近制作了一个自行车行程分析仪,您可以输入行程​​距离和该行程的平均速度,并计算您的时间,将您当前的速度与最低速度,最大速度和所有速度的平均速度进行排名输入到目前为止,然后按速度,距离和时间绘制您的进度(最近10次旅行)。事情一直在按计划进行,除非我必须删除记录(不正确的记录),并正常运行程序(由于数据库对索引执行的操作,编号全部搞砸了)。我添加了一个功能来帮助减轻其中一些,但它并没有完全解决问题。 (它不会显示10条记录,因为在指定的时间间隔内缺少某些记录号。)所以现在,我正在改进它,并找到了两种方法。

我找到了一种简单的递归方式,以及相应的迭代方法。


递归方式:

private int calculateOffset(int min, int max)
{
    int actualTripNumber = 0, expectedTripNumber = 0, totalOffset = 0;
    try
    {
        resultSet = statement.executeQuery("SELECT TripNumber FROM BikeTripRecords WHERE TripNumber > " + 
            ((max == 0) ? String.format("(SELECT max(TripNumber) FROM BikeTripRecords) - %d", maxShowableRecords) : 
                String.format("%d AND TripNumber < %d", min, max))
            );
        //we could set expectedTripNumber = min + 1 (and then offset = min + 1), but that would cost one instruction
        while (resultSet.next())
        {
            actualTripNumber = resultSet.getInt(1);     //get the actualTripNumber
            totalOffset += ((expectedTripNumber > 0) ? actualTripNumber - expectedTripNumber : actualTripNumber - (min + 1));   //calculate the offset
            expectedTripNumber = actualTripNumber + 1;  //we expect the next actualTripNumber to be one more than the current one
        }
    }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  //You KNOW something went wrong with a negative return value; this could be replaced by System.exit(1), however
    }

    //conditional tail recursion; this should end with the last recursive call to return 0
    if (totalOffset > 0)
    {
        //if this function was called from the outside 
        if (max == 0)
        {
            //we assign to max the first number from the resultSet
            int newMax = resultSet.getInt(1);
            totalOffset += calculateOffset(newMax - totalOffset, newMax);
        }
        else
        {
            totalOffset += calculateOffset(min - totalOffset, min);
        }
    }
    return totalOffset;
}

迭代方式:

private int calculateOffset()
{
    //This version of calculateOffset() will be ITERATIVE, not recursive (and will use a helper function)
    int totalOffset = 0, intervalOffset = 1000; //giving intervalOffset a garbage value (so that we could use it in the while loop)
    int minimum = 0, maximum = 0;
    //this is the first calculation; we obtain the max(TripNumber) from BikeTripRecords (this method will only be called ONCE)
    try
    {
        resultSet = statement.executeQuery("SELECT max(TripNumber) FROM BikeTripRecords");
        resultSet.next();
        maximum = resultSet.getInt(1);  //fetching maximum
        minimum = maximum - maxShowableRecords;     //while we are at it, we might as well assign minimum a value here, too...
        }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  // You know something went wrong when the return value is negative!!
    }
    //we simply add to totalOffset the return value of our helper function (the offset of the intervals specified) while it doesn't return 0
    while (intervalOffset > 0)
    {
        intervalOffset = getIntervalOffset(minimum, maximum);   //get the intervalOffset
        totalOffset += intervalOffset;      //add it to the totalOffset
        //recalculate maximum, minimum
        maximum = minimum;
        minimum -= intervalOffset;
    }
    return totalOffset;
}

//helper function
private int getIntervalOffset (int min, int max)
{
    int offset = 0; //the value of this variable will be the return value (if everything goes according to plan)
    int actualTripNumber = 0, expectedTripNumber = 0;
    try
    {
        resultSet = statement.executeQuery(String.format("SELECT TripNumber FROM BikeTripRecords WHERE TripNumber > %d AND TripNumber <= %d", min, max));
        //computing the offset of the interval
        while (resultSet.next())
        {
            actualTripNumber = resultSet.getInt(1);     //getting the actualTripNumber
            //the only offset there should be the first time around should be the difference between the actualTripNumber and one more than the min
            //otherwise, the offset should be the difference between the actualTripNumber and the expectedTripNumber
            offset += ((expectedTripNumber > 0) ? actualTripNumber - expectedTripNumber : actualTripNumber - (min + 1));    
            expectedTripNumber = actualTripNumber + 1;  //the expectedTripNumber should be one more than the actualTripNumber
        }
    }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  // How you KNOW something went wrong....
    }
    return offset;
}

两个代码片段都检查k个间隔(k是正整数)。我难以理解的是计算每种方法的算法复杂性。两种方式的关键部分完全相同:一个执行正好10-m次的while循环(m是被检查区间中计算的丢失记录数)。在这里,我们可以肯定地说m高于10。我提出的两种方法的复杂性是相对于k和sum(mj,j在1和k之间)是线性的,即32k-(2+) 3 sum(mj,j介于1和k-1之间))用于递归方式和4 + 31k-3 sum(mj,j在1和k-1之间)。 (这里,mj读取“m sub j”。)两种算法的复杂性是否会摊销,还是O(max {k,sum(mj,j介于1和k-1之间))?

2 个答案:

答案 0 :(得分:1)

为什么不让自己避免头痛并获得最近的10个结果?

由于您使用的是德比,因此可以使用以下方法限制结果:

statement.setMaxRows(10); 

然后,假设您的TripNumber列是自动递增的ID,您只需订购结果:

SELECT TripNumber FROM BikeTripRecords 
ORDER BY TripNumber DESC

答案 1 :(得分:0)

对于递归方法,我必须在try块的开头添加以下代码:

if (max == 0)
{
    resultSet = statement.executeQuery("SELECT max(TripNumber) FROM BikeTripRecords");
    resultSet.next();
    min = resultSet.getInt(1);
}

这可能是错误的代码练习,因为

  • 我必须多次说“SELECT max(TripNumber)FROM BikeTripRecords”
  • 第一次
  • minmax未使用!!

看到这一切,我只是决定采用迭代方法,因为这是阻力较小的路径。

另外,我刚接到我的“AHA!”时刻:对于从开始到完成的两种方法,resultSet.next()将正确返回10次,因此两种方法的关键部分都具有30的复杂度。因此,两种方法都是摊销的。尽管如此,我仍然采用迭代方法,因为这是更好的练习。