Early math

Here is what I was doing at 5:30 this morning:

Imagine a grid that contained a list of an arbitrary number of things, but displayed only 7 at a time. Suppose the total number is 35. If, when rendering the list, you wanted to have it take you to the “page” on which a specific item appears, how do you figure out what pages that is, assuming everything sorts consistently?

After a lot of scribbling on my white board, here’s what I came up with:

1. Find the position of the item in the overall list. Let’s says it’s position 25.

2. If the position mod 7 != 0 then the page is (count / 7) + 1; in this case (25/7)+1 or 4; otherwise, page is just count/7 or 3.

3. To translate the display page in to a “start at” value (where to start looking in the list), you then have to do ((page-1)*7)+1. In my example, this gets you a value of ((4-1)*7)+1 = 22. What that means is that when I show the list, I need to start at item #22 and display the next 7 items in order to make sure I capture the . (Since 25 > 22 and 25 < 29), we get the section of the list we were looking for. This seems incredibly complicated for something so simple. I know that an .NET gridview control does this natively but I could not use one of those for good reasons. Yes, that's right, I was sitting in my office doing modulus arithmetic at 5:30 this morning, while the rest of the world was sleeping.