I have a solution which takes m-element array
returns an n-element array
distributed evenly. But for some value of m it generates stderr
.
For example, if array will have 15 elements it stderr
will be:
class SpredArrayClass
{
var $array = [1,2,3,4,5,6,7,8,9,9,10,11,12,13,14,15];
function spreadOutArray(array $array = [], $targetOutputLength = 10) {
$array = $this->array;
$originalArrayLength = count($array);
if ($originalArrayLength == 0) {
return false;
}
if ($originalArrayLength <= $targetOutputLength) {
return $array;
}
$output = [];
$interval = round($originalArrayLength / $targetOutputLength);
for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
$output[] = $array[$index];
}
return array_reverse($output);
}
}
Problem seem to be in this part:
$output = [];
$interval = round($originalArrayLength / $targetOutputLength);
for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
$output[] = $array[$index];
}
Undefinded offset stderr
appears at this line: $output[] = $array[$index];
Demo of code execution here: http://ideone.com/UrF9UK
You round too early. The steps ($interval) should be exact, because if the rounding is upward, the steps will bring you too fast to the start of the array and lead to negative indexes.
So only round when you use the resulting index:
$interval = $originalArrayLength / $targetOutputLength;
for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
$output[] = $array[round($index)];
}
Your Problem stems from the the condition in your
for
Loop. Change it to this:
$output = [];
$interval = round($originalArrayLength / $targetOutputLength);
// JUST KEEP LOOPING & PUSHING TILL SO LONG AS $index IS GREATER THAN 0;
for($index = $originalArrayLength - 1; $index>=0; $index -= $interval) {
$output[] = $array[$index];
}