Day 0: Weighted Mean | 10 Days Of Statistics | HackerRank Solution

Hello coders, today we are going to solve Day 0: Weighted Mean HackerRank Solution which is a Part of 10 Days of Statistics Series.

Day 0: Weighted Mean

Contents

Objective

In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean.

Task

Given an array, X, of N integers and an array, W, representing the respective weights of X‘s elements, calculate and print the weighted mean of X‘s elements. Your answer should be rounded to a scale of 1 decimal place (i.e., 12.3 format).

Example

X = [1, 2, 3]
W = [5, 6, 7]
The array of values X[i] * W[i] = [5, 12, 21]. Their sum is 38. The sum of W = 18. The weighted mean is 38/18 = 2.1111. . . . Print 2.1 and return.

Function Description
Complete the weightedMean function in the editor below.

weightedMean has the following parameters:
– int X[N]: an array of values
– int W[N]: an array of weights

Prints
– float: the weighted mean to one decimal place

Input Format

The first line contains an integer, N, the number of elements in arrays X and W.
The second line contains N space-separated integers that describe the elements of array X.
The third line contains N space-separated integers that describe the elements of array W.

Output Format

Print the weighted mean on a new line. Your answer should be rounded to a scale of 1 decimal place (i.e., 12.3 format).

Sample Input

STDIN           Function
-----           --------
5               X[] and W[] size n = 5
10 40 30 50 20  X = [10, 40, 30, 50, 20]  
1 2 3 4 5       W = [1, 2, 3, 4, 5]

Sample Output

32.0

Explanation

We use the following formula to calculate the weighted mean:
Mw = 480 / 15 = 32.0
And then print our result to a scale of 1 decimal place (32.0) on a new line.

Solution – Day 0: Weighted Mean Solution

C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() 
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    
    int n; cin>>n; int a[n+4], w;
    double num=0.0, den=0.0;
    
    for(int i=0;i<n;i++) 
        cin>>a[i];
    
    for(int i=0;i<n;i++) 
    {
        cin>>w;
        den+=w;
        num+=(a[i]*w);
    }
    
    double wmean = (double)(num/den);
    
    printf("%0.1f\n", wmean);
    
    return 0;
}

Python

size = int(input())
numbers = list(map(int, input().split()))
weighted = list(map(int, input().split()))

sum_items = 0
for i in range(size):
    sum_items = sum_items + (numbers[i] * weighted[i])

print(round(sum_items/sum(weighted), 1))

Disclaimer: The above Problem (Day 0: Weighted Mean) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published.