Evenly select N elems from array

Posted by ninuhadida on Stack Overflow See other posts from Stack Overflow or by ninuhadida
Published on 2010-03-15T23:57:22Z Indexed on 2010/03/15 23:59 UTC
Read the original article Hit count: 369

Filed under:
|

Hi,

I need to evenly select n elements from an array. I guess the best way to explain is by example.

say I have:

array [0,1,2,3,4] and I need to select 3 numbers.. 0,3,4.

of course, if the array length <= n, I just need to return the whole array.

I'm pretty sure there's a defined algorithm for this, been trying to search, and I took a look at Introduction to algorithms but couldn't find anything that met my needs (probably overlooked it)

The problem I'm having is that I can't figure out a way to scale this up to any array [ p..q ], selecting N evenly elements.

note: I can't just select the even elements from the example above..

A couple other examples;

array[0,1,2,3,4,5,6], 3 elements ; I need to get 0,3,6
array[0,1,2,3,4,5], 3 elements ; I need to get 0, either 2 or 3, and 5

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about algorithm-design