Reputation: 35
The moving averages based on 5 numbers of these win numbers is a moving part. So if the win numbers are: 3-4-5-6-7-8-4-5-6-33-23-12-5-1 Then the first moving average is based on 3-4-5-6-7 divided by 5 Then the second moving average is based on 4-5-6-7-8 divided by 5 Then the third moving average is based on 5-6-7-8-4 divided by 5
I tried creating a array but it didnt work.
<?php
$existing = [];
$win_numbers = [];
for ($rnd=1;$rnd<=250;$rnd++)
{
$randoms[] = mt_rand(0,36); // see this block for generating randoms
}
echo "Random Numbers:<br>";
echo implode('-', $randoms).PHP_EOL;
echo "<br><br>";
$i = 0;
foreach($randoms as $rnd){
$i++;
if(in_array($rnd,$existing)){
$win_numbers[] = $i;
$i=1;
$existing = [];
}
$existing[] = $rnd;
}
echo "Win Numbers:<br>";
echo implode('-',$win_numbers);
echo "<br><br>";
echo "Moving Averages:<br>";
?>
Upvotes: 0
Views: 965
Reputation: 38542
You can do this way, Also it can be optimize with couple of methods like array_sum()
and array_slice()
<?php
// Function to print moving average
function movingAverage($win_numbers, $average_for)
{
foreach($win_numbers as $key=>$value){
$win_number_consecutive_5 = array_slice($win_numbers, $key, $average_for);
if(count($win_number_consecutive_5) == $average_for) {
$win_averages[] = array_sum($win_number_consecutive_5) / $average_for;
}
}
return $win_averages;
}
echo "Moving Averages:<br>";
$win_numbers = explode('-','3-4-5-6-7-8-4-5-6-33-23-12-5-1');
$average_for = 5;
echo implode('-',movingAverage($win_numbers, $average_for));
?>
WORKING DEMO: https://3v4l.org/GO0Ai
Upvotes: 2
Reputation: 23958
If you loop the array with a for loop and use array_slice then you can get a rolling average.
for($i=0;$i<count($randoms)-4;$i++){
$avg[] = array_sum(array_slice($randoms, $i, 5))/5;
}
Example: https://3v4l.org/XUdlP
Upvotes: 0