136. Generic Moving Average Filter

In embedded signal processing, raw sensor data is often noisy. A common technique to smooth this data is a Moving Average Filter. Implementing a separate filter class for every data type (int, float, double) and window size results in code duplication. Your task is to implement a Class Template named MovingAverage. It must accept:

  1. typename T: The data type of the samples (e.g., float, int).
  2. int WindowSize: The number of samples to average (Non-Type Template Parameter).

The class must maintain a circular buffer (array) of WindowSize elements. Implement the method:

  • T addSample(T sample):
    • Adds the new sample to the buffer, overwriting the oldest one.
    • Returns the current average of all samples in the buffer.
    • Note: Until the buffer is full for the first time, average only the samples added so far.

Program Flow:

  1. The main function instantiates a MovingAverage<float, 4> (Window Size = 4).
  2. Read integer N (number of inputs).
  3. Loop N times.
  4. Read float sample.
  5. Call filter.addSample(sample).
  6. Print the returned average formatted to 2 decimal places.

Input Format:

  • First line: Integer N.
  • Next N lines: Float sample.
  • Input provided via stdin.

Output Format:

  • For each sample, print: Avg: <value>
  • Value must be formatted to 2 decimal places (e.g., 10.50).

Example: 

Example 1 (Window Size 4)

Input:

5
10.0
20.0
30.0
40.0
50.0

Output:

Avg: 10.00
Avg: 15.00
Avg: 20.00
Avg: 25.00
Avg: 35.00

Explanation:

  1. {10} -> 10/1 = 10
  2. {10, 20} -> 30/2 = 15
  3. {10, 20, 30} -> 60/3 = 20
  4. {10, 20, 30, 40} -> 100/4 = 25
  5. {50, 20, 30, 40} -> 140/4 = 35 (10 is overwritten)

Constraints:

  • N range: 1 to 20
  • WindowSize fixed at 4 for tests.
  • No dynamic memory (new, malloc).
  • Must use templates.

 

 

 

 

Loading...

Input

5 10.0 20.0 30.0 40.0 50.0

Expected Output

Avg: 10.00 Avg: 15.00 Avg: 20.00 Avg: 25.00 Avg: 35.00