Electronic Elves Residence
Add
{code} {code} == == * * _ _ [] * #

204

2017-01-12 12:44:40
$window = function ($window_size) {
    $window = [];
    $window_ptr = 0;
    $avg = 0;
    while (true) {
        $value = (yield $avg);
        if ($value === null) break;
        $window[$window_ptr] = $value;
        $window_ptr = ($window_ptr + 1) % $window_size;
        $avg = array_sum($window) / count($window);
    }
};

/** @var Generator $windowed_avg */
$windowed_avg = $window(10);
foreach ([10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 10, 10, 10] as $v) {
    $avg = $windowed_avg->send($v);
    echo "sent $v got $avg\n";
}