2
$\begingroup$

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]
$\endgroup$
1
  • $\begingroup$ first find the index of current_item, then move right or left on the array. $\endgroup$ Commented Apr 2, 2020 at 12:06

1 Answer 1

1
$\begingroup$

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$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.