The challenge is to create an algorithm for generating a specifically-sized subset of numbers in a sequence based on the current position in that sequence.
While navigating through the many pages of content on a busy site like Stack Overflow or Digg it is often desirable to give the user a way to quickly jump to the first page, the last page or a specific page which is near the current page they are viewing.
Requirements
- First and last page numbers are always displayed
- The subset of page numbers will contain the current page number as well as page numbers before and/or after it (depending on current page)
- The subset of page numbers will
always be a fixed number of pages and
can never exceed or fall short of
that fixed number unless:
totalPages < fixedWidth
- The position of the current page
number in the subset is fixed
unless:
1 <= currentPage < (fixedWidth - defaultPostion)
or(totalPages - currentPage) < (fixedWidth - defaultPostion)
- Output should indicate when there is a gap greater than 0 between the first page of data and the first page of the subset as well as between the last page of the subset and last page of data. This indicator should appear at most once in either position.
If you can't picture this yet, take a look at your Stack Overflow profile under questions/answers. If you have more than 10 of either one, you should see paging links at the bottom which are generated in exactly this fashion. That, or scroll to the bottom of http://digg.com and observe their paging control.
Examples
All examples assume a subset size of 5 and the current page in position 3, but these
should be configurable in your solution. ...
indicates the gap between page numbers, [x]
indicates the current page.
Current Page: 1 of 30
Output: [x][2][3][4][5]...[30]
Current Page: 2 of 30
Output: [1][x][3][4][5]...[30]
Current Page: 13 of 30
Output: [1]...[11][12][x][14][15]...[30]
Current Page: 27 of 30
Output: [1]...[25][26][x][28][29][30]
Current Page: 30 of 30
Output: [1]...[26][27][28][29][x]
Current Page: 3 of 6
Output: [1][2][x][4][5][6]
Current Page: 4 of 7
Output: [1][2][3][x][5][6][7]
Additional Clarifications
- First and last pages do not count toward
numberOfPages
unless they are sequentially part ofnumberOfPages
as in[1][x][3][4][5]...[30]
or[1]...[26][27][28][x][30]
, but not in[1]...[8][9][x][11][12]...[30]
- No gap indicator should be included if the distance
between either end of the subset and the first
or last page is less than 1. Thus, it is possible
to have a non-breaking sequence of pages up to
fixedWidth + 2
as in[1][2][3][x][5][6]...[15]
or[1][2][3][x][5][6][7]
Solutions in any and all languages are welcome.
Good luck!