开发者

Custom paging algorithm to calculate pages to display

开发者 https://www.devze.com 2022-12-21 03:53 出处:网络
I\'m working on a custom data pager for a custom google maps control. The control needs to work out what range of pages to display. For example, if the user is on page 6 then the control must display

I'm working on a custom data pager for a custom google maps control. The control needs to work out what range of pages to display. For example, if the user is on page 6 then the control must display pages 1 through to 10. If the user is on page 37, then the control must display pages 30 throught to 40.

The variables I have available are:

X - Total results (points on the map)

Y - The current pag开发者_StackOverflow社区e size. i.e. the amount of points per page.

Z - The current page being displayed

Q - The number of page numbers to display (a const of 10)

I have come up with:

Starting Index = Z - (Z % Q)

Ending Index = Z - (Z % Q) + Q

This, however, doesn't work for when the current page is less than 10. It also doesn't figure out whether there is a max page reached, i.e. we always display a full range of 10. However, if we display the range 30-40 the final page could actually be 38.

If anyone can come up with a more elegant algorithm it would be appreciated.


It might be easier if you think in terms of chapters.

Say each set of pages is a chapter, chapter are numbered starting from 0, 1, 2,...

Then the rth chapter has pages in the range

Qr + 1 <= page <= Q(r+1)

Now consider floor(page/Q). This is r if page is not a multiple of Q, otherwise it is r+1.

Given an r, you can find out the pages of the chapter as Lower = Qr + 1 and higher = min(max, Q(r+1)).

So you can do this.

if (Z < 1 || Z > max_page) { error;}

if (Z % Q == 0) {
    r = Z/Q - 1; // integer division, gives floor.
}
else {
    r = Z/Q; // floor.
}

Begin = Q*r + 1;
End = Min (Q*(r+1), max_page);

To get rid of the if, you can now replace it with

if (Z < 1 || Z > max_page) { error;}

r = (Z-1)/Q;
Begin = Q*r + 1;
End = Min (Q*(r+1), max_page);

This works because:

Qr + 1 <= Z <= Q(r+1) if and only if

Qr <= Z-1 <= Qr + (Q-1).

Thus floor((Z-1)/Q) = r.


Here we go:

def lower(Z):
  return (Z - 1) // Q * Q + 1

def upper(Z):
  return min(int(ceil(X / Y)), ((Z - 1) // Q + 1) * Q)

// is integer division.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号