views:

53

answers:

1

I have a 2 sets of intervals, like:

xCoords: (0, 60], (60, 120], (120, 180] ...
yCoords: (0, 60], (60, 120], (120, 180] ...

The size of each interval is guaranteed to be the same, but the size of an xCoord interval doesn't have to be the size of a yCoord interval. (I could make that sacrifice in generality if necessary for optimization; but it's possible in the future I may want different yCoord and xCoord sizes.)

I also have given pairs, such as:

(x, y)
(0, 60)
(123, 52)
(34, 196)

Sample answers for the above:

(lowerBoundX, lowerBoundY)
(0, 60)
(120, 0)
(0, 180)

What is the most optimal way to find which interval they belong in? Here is what I have currently:

        // we'll need to be able to access these outside of the loops
        uint minWidth = 0;
        uint minHeight = 0;

        for (minWidth = 0; minWidth + cellWidth <= xToFind; minWidth += cellWidth) ;
        for (minHeight = 0; minHeight + cellHeight <= yToFind; minHeight += cellHeight) ;

At the end of this loop, minWidth represents the lower bound of the x interval, and minHeight represents the lower bound of the y interval.

So, can I find a faster way to do this? A profiler identifies the for loops as the slowest parts of the function.

+3  A: 

If the sizes in X are constant, you can find this much more efficiently:

public int GetPosition(int size, int coord)
{
    int index = coord / size;
    return index * size;
}

Then you can do:

lowerBoundX = GetPosition(xSize, xCoord);
lowerBoundY = GetPosition(ySize, yCoord);
Reed Copsey
The reason this works is because int / int = int, with the decimals being truncated. When you multiply the divisor back on, you get the lower bound.
Michael Madsen
Integer division is great for optimizing a lot of these sorts of routines. :) - However, if your cell sizes changed each step, and weren't constant, you'd probably have to revert to a more elaborate algorithm (although there'd still be much better options than looping...)
Reed Copsey