自定义分页算法来计算要显示的页面
我正在为自定义谷歌地图控件开发自定义数据分页器。该控件需要计算出要显示的页面范围。例如,如果用户在第 6 页,则控件必须显示第 1 页到第 10 页。如果用户在第 37 页,则控件必须显示第 30 页到第 40 页。
我可用的变量有:
X - 总结果(地图上的点)
Y - 当前页面大小。即每页的点数。
Z - 当前显示的页面
Q - 要显示的页码数(常量为 10)
我想出了:
起始索引 = Z - (Z % Q)
结束索引 = Z - (Z % Q) + Q
然而,这是,当当前页面小于 10 时不起作用。它也不会计算是否达到最大页面,即我们总是显示 10 的完整范围。但是,如果我们显示范围 30-40最后一页实际上可能是 38。
如果有人能想出一个更优雅的算法,我们将不胜感激。
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 page 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你按照章节来思考,可能会更容易。
假设每组页面都是一个章节,章节编号从 0, 1, 2,... 开始,
那么第 r 个章节的页面范围为
Qr + 1 <= page <= Q(r+1)
现在考虑楼层(页/Q)。如果 page 不是 Q 的倍数,则为 r,否则为 r+1。
给定 r,您可以通过 Lower = Qr + 1 和 upper = min(max, Q(r+1)) 找到该章的页数。
所以你可以这样做。
要摆脱 if,您现在可以将其替换为
This Works because:
Qr + 1 <= Z <= Q(r+1) 当且仅当
Qr <= Z-1 <= Qr + (Q-1)。
因此floor((Z-1)/Q) = r。
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.
To get rid of the if, you can now replace it with
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:
//
is integer division.