Oli Warner About Contact Subscribe

Help with an algorithm

Saturday, 3 March 2007 personal

Hi guys. I’m just putting the finishing touches on the forums (the version that none of you can see yet) and I’m trying to sexify the paging/pagination.

I’m aiming for a system that works like this:

  1. It will always display 9 numbers
  2. When the range is more than 9, it will truncate around the currently selected page
  3. When truncating, it should always show at least one number either side of the current page and the three pages closest to the extremes (min and max)

Some examples would be (* denotes selection):

1 2 3 … 8 9 10 11 12 13*
1 2\* 3 4 5 6 … 12 13 14
1 2 3 … 7 8\* 9 … 12 13 14

Okay. Given that you know how many pages there are in total and which page is currently selected, how would you work out those output strings?

Update: I’ve come up with this massive, ugly but functional beast. Not pretty. If anybody has any better suggestions, please put them forward.

If pages > 9 Then
If pages - 4 <= pagenumber Then ' 1 2 3 ... 8 9 10 11 12 13*
For i As Integer = 1 To 3
ret.Append(PageLink(base, i, pagenumber))
Next
ret.Append("... ")
For i As Integer = pages - 5 To pages
ret.Append(PageLink(base, i, pagenumber))
Next

ElseIf 5 >= pagenumber Then ' 1 2* 3 4 5 6 ... 12 13 14
For i As Integer = 1 To 6
ret.Append(PageLink(base, i, pagenumber))
Next
ret.Append("... ")
For i As Integer = pages - 2 To pages
ret.Append(PageLink(base, i, pagenumber))
Next

Else ' 1 2 3 ... 7 8* 9 ... 12 13 14
For i As Integer = 1 To 3
ret.Append(PageLink(base, i, pagenumber))
Next
ret.Append("... ")
For i As Integer = pagenumber - 1 To pagenumber + 1
ret.Append(PageLink(base, i, pagenumber))
Next
ret.Append("... ")
For i As Integer = pages - 2 To pages
ret.Append(PageLink(base, i, pagenumber))
Next
End If
Else
For i As Integer = 1 To pages
ret.Append(PageLink(base, i, pagenumber))
Next
End If