Question

Suppose I have the array:

[2, 3, 4, 5, 6, 7, 8, 9]

Now based on few parameters:

  1. current_item - currently selected item.
  2. select_size - selection size, always odd.

I want to get a sublist of the list that follows the conditions:

  1. current_item should be in middle of sublist if that is possible.
  2. In case when there is not enough elements on left/right of the list, use the ones from right/left.

Examples:

list: [2, 3, 4, 5, 6, 7, 8, 9]
current_item: 5
select_size: 3

result: [4, 5, 6]


list: [2, 3, 4, 5, 6, 7, 8, 9]
current_item: 2
select_size: 5

result: [2, 3, 4, 5, 6]

list: [2, 3, 4, 5, 6, 7, 8, 9]
current_item: 8
select_size: 5

result: [5, 6, 7, 8, 9]
Was it helpful?

Solution

Let the index of the central item be $c$, and the length of the list be $2r+1$. We assume that the indices of the list are $0,\ldots,n-1$.

There are four cases to consider:

  • If $n > 2r+1$, then the results are undefined (per your post).
  • If $0 \leq c-r$ and $c+r \leq n-1$, then you just take elements $c-r,\ldots,c+r$.
  • If $c-r < 0$, then you take elements $0,\ldots,2r$.
  • If $c+r \geq n$, then you take elements $n-2r-1,\ldots,n-1$.

In the latter two cases, we are guaranteed to be within bounds since $n > 2r+1$.

Licensed under: CC-BY-SA with attribution
Not affiliated with cs.stackexchange
scroll top