Note that there are some explanatory texts on larger screens.

plurals
  1. POEvenly select N elems from array
    primarykey
    data
    text
    <p>I need to <strong>evenly</strong> select <em>n</em> elements from an array. I guess the best way to explain is by example.</p> <p>say I have:</p> <p>array [0,1,2,3,4] and I need to select 3 numbers.. 0,2,4.</p> <p>of course, if the array length &lt;= <em>n</em>, I just need to return the whole array.</p> <p>I'm pretty sure there's a defined algorithm for this, been trying to search, and I took a look at <em>Introduction to algorithms</em> but couldn't find anything that met my needs (probably overlooked it)</p> <p>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.</p> <p>note: I can't just select the even elements from the example above..</p> <p>A couple other examples;</p> <p>array[0,1,2,3,4,5,6], 3 elements ; I need to get 0,3,6<br> array[0,1,2,3,4,5], 3 elements ; I need to get 0, either 2 or 3, and 5</p> <p>EDIT:</p> <p>more examples:<br> array [0,1,2], 2 elems : 0,2<br> array [0,1,2,3,4,5,6,7], 5 elems : 0,2, either 3 or 4, 5,7</p> <p>and yes, I'd like to include first and last elements always.</p> <p>EDIT 2:</p> <p>what I was thinking was something like .. first + last element, then work my way up using the median value. Though I got stuck/confused when trying to do so.</p> <p>I'll take a look at the algo you're posting. thanks!</p> <p>EDIT 3:</p> <p>Here's a souped up version of <em>incrediman</em> solution with PHP. Works with associative arrays as well, while retaining the keys.</p> <pre><code>&lt;?php /** * Selects $x elements (evenly distributed across $set) from $set * * @param $set array : array set to select from * @param $x int : number of elements to select. positive integer * * @return array|bool : selected set, bool false on failure */ ///FIXME when $x = 1 .. return median .. right now throws a warning, division by zero function select ($set, $x) { //check params if (!is_array($set) || !is_int($x) || $x &lt; 1) return false; $n = count($set); if ($n &lt;= $x) return $set; $selected = array (); $step = ($n - 1) / ($x - 1); $keys = array_keys ($set); $values = array_values($set); for ($i=0; $i&lt;$x; $i++) { $selected[$keys[round($step*$i)]] = $values[round($step*$i)]; } return $selected; } ?&gt; </code></pre> <p>You can probably implement an <a href="http://www.php.net/manual/en/spl.iterators.php" rel="noreferrer">Iterator</a> but I don't need to take it that far.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload