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:
PHP Notice: Undefined offset: -3 PHP Notice: Undefined offset: -1
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