1

I've racked my brain over this one and it's harder than it looks.

Please could some hardcore hacker out there show me a nice way to implement the following:

Given an indexed list of unknown size And a known max range size [say 10] (page size, i.e. how many results will be returned) When I give
this function an index (within the range of the indexed list) Then it will return me a new range And the returned range should be of size
10, if possible And the returned range should always try to include
5 indexes before the input index And the returned range should try to include 4 indexes after the input index

To see this working, goto Google and search for something. You get a set of results with some links (1 - 10) When you click any link after page 6, the results will always have five links before and four links after the current page.

I just want to see how this is done, logically.

If anybody has a cool linq suggestion then I'd be really grateful.

I've already made this code work, but it's verbose and with lots of 'ifs' and 'elses' - I just know there's an elegant way to do it.

The problems I found where:

(1) Having a range that's less than the offset (i.e. only three results).

(2) Entering a index that's very close to the start or end of the input range.

I've searched the net over and over but can't find a simple (language agnostic) way to express this logic.

Thanks,

1 Answers1

1

You can use a max function (language agnostic) to achieve this.

start_index = max(1, index - offset)
end_index = index + offset
recursive
  • 83,943
  • 34
  • 151
  • 241
  • Hi, thanks for this answer. I tried this, but what if we have only three results? - end_index will be larger than the entire range. I did say it was deceptive.. – user2960017 Dec 16 '13 at 22:09
  • You said the list was of unknown size. If you know the size, you can fit within the list. If it's an unknown size list, guaranteeing you haven't exceeded the bounds is of course impossible. – recursive Dec 16 '13 at 23:26