Peter’s blog ✴ Week 122 ✴ 19 July 2021

THE WEEKLY CHALLENGE
Stream and points

The Perl Camel

Task 1

Average of stream

You are given a stream of numbers, @stream. Write a script to print the average of the stream at every point.

Examples


Input: @N = (10, 20, 30, 40, 50, 60, 70, 80, 90, ...)
Output:      10, 15, 20, 25, 30, 35, 40, 45, 50, ...

Average of first number is 10.
Average of first 2 numbers (10+20)/2 = 15
Average of first 3 numbers (10+20+30)/3 = 20
Average of first 4 numbers (10+20+30+40)/4 = 25 and so on.

Analysis

This is pretty straightforward and probably lends itself to a one-liner. I have chosen, for the sake of clarity to expand it to a few lines in which $j loops over the indices of @stream and at each point accumulates a total.

That total divided by the current $j + 1 gives the average to date.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 3, 1, 4, 1, 5, 9

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-07-19
use utf8;     # Week 122 - task 1 - Average of stream
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

average_of_stream(10, 20, 30, 40, 50, 60, 70, 80, 90);
average_of_stream(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5);
average_of_stream(1, 2.5, 3.78, -6.31, 5);

sub average_of_stream {
    
    my (@stream, $total, $j, @average);
    
    # initialise
    @stream = @_;
    $total = 0;
    for $j (0 .. $#stream) {
        $total += $stream[$j];
        $average[$j] = sprintf('%.2f', $total / ($j + 1));
    }
    
    say qq[\nInput:  (] . join(', ', @stream) . ')';
    say qq[Output: (] . join(', ', @average) . ')';
}

9 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  (10, 20, 30, 40, 50, 60, 70, 80, 90)
Output: (10.00, 15.00, 20.00, 25.00, 30.00, 35.00, 40.00,
   45.00, 50.00)

Input:  (-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5)
Output: (-5.00, -4.50, -4.00, -3.50, -3.00, -2.50, -2.00,
   -1.50, -1.00, -0.50, 0.00)

Input:  (1, 2.5, 3.78, -6.31, 5)
Output: (1.00, 1.75, 2.43, 0.24, 1.19)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain