Source : https://www.hackerrank.com/challenges/s10-weighted-mean
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers and an array, , representing the respective weights of 's elements, calculate and print the weighted mean of 's elements. Your answer should be rounded to a scale of decimal place (i.e., format).
Input Format
The first line contains an integer, , denoting the number of elements in arrays and .
The second line contains space-separated integers describing the respective elements of array .
The third line contains space-separated integers describing the respective elements of array .
Constraints
- , where is the element of array .
- , where is the element of array .
Output Format
Print the weighted mean on a new line. Your answer should be rounded to a scale of decimal place (i.e., format).
Sample Input
510 40 30 50 201 2 3 4 5
Sample Output
32.0
Explanation
We use the following formula to calculate the weighted mean:
And then print our result to a scale of decimal place () on a new line.
Source : https://www.hackerrank.com/challenges/s10-weighted-mean
Solution
// github.com/RodneyShag | |
import java.util.Scanner; | |
public class Solution { | |
public static void main(String[] args) { | |
/* Save input */ | |
Scanner scan = new Scanner(System.in); | |
int size = scan.nextInt(); | |
int [] elements = new int[size]; | |
int [] weights = new int[size]; | |
for (int i = 0; i < size; i++) { | |
elements[i] = scan.nextInt(); | |
} | |
for (int i = 0; i < size; i++) { | |
weights[i] = scan.nextInt(); | |
} | |
scan.close(); | |
/* Calculate weighted mean */ | |
int total = 0; | |
int totalWeights = 0; | |
for (int i = 0; i < size; i++) { | |
total += elements[i] * weights[i]; | |
totalWeights += weights[i]; | |
} | |
double weightedMean = (double) total / totalWeights; | |
System.out.format("%.1f", weightedMean); | |
} | |
} |
No comments:
Post a Comment