Find mean of subarray means in a given array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n and an integer m. Our task is to Find mean of subarray means in a given array.

Code Description − Here, we need to find the mean of array as the mean of means of subarray of size m.

Let’s take an example to understand the problem,

Input

arr[] = {2, 5, 3, 6, 1}, m = 3

Output

3.78

Explanation

All subarrays of size m are {2, 5, 3}, {5, 3, 6}, {3, 6, 1}
Means of means of subarray of size m,

$$(\left(\frac{2+5+3}{3}\right)+\left(\frac{5+3+6}{3}\right)+\left(\frac{3+6+1}{3}\right))/3=\left(\frac{10}{3}\right)+\left(\frac{14}{3}\right)+\left(\frac{10}{3}\right)/3=34/3/3=3.78$$

Solution Approach

A simple solution to the problem is by finding all subarrays of size m and finding their means. Then add all these means and divide it by the count of subarrays. And return the result.

Another more efficient approach is by using the sliding window algorithm. We will find a finding of size m starting from index 0. For each window find the mean and sum. And at the end divide the sum by window count and return the value.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
float calcMeanOfSubarrayMeans(int arr[], int n, int m) {
   float meanSum = 0, windowSum = 0;
   for (int i = 0; i < m; i++)
      windowSum += arr[i];
      meanSum += (windowSum / m);
   for (int i = 0; i < n; i++) {
      windowSum = windowSum - arr[i - m] + arr[i];
      meanSum += (windowSum / m);
   }
   int windowCount = n - m + 1;
   return (meanSum / windowCount);
}
int main() {
   int arr[] = { 4, 1, 7, 9, 2, 5, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   int m = 3;
   cout<<"The mean of subarray means is "<<calcMeanOfSubarrayMeans(arr, n, m);
   return 0;
}

Output

The mean of subarray means is 8.06667
raja
Published on 12-Mar-2021 06:40:03
Advertisements