Source : https://www.hackerrank.com/challenges/s10-standard-deviation
Objective
In this challenge, we practice calculating standard deviation. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers, calculate and print the standard deviation. Your answer should be in decimal form, rounded to a scale of decimal place (i.e., format). An error margin of will be tolerated for the standard deviation.
Input Format
The first line contains an integer, , denoting the number of elements in the array.
The second line contains space-separated integers describing the respective elements of the array.
Constraints
- , where is the element of array .
Output Format
Print the standard deviation on a new line, rounded to a scale of decimal place (i.e., format).
Sample Input
510 40 30 50 20Sample Output
14.1Explanation
First, we find the mean:
Next, we calculate the squared distance from the mean, , for each :
Now we can compute , so:
Once rounded to a scale of decimal place, our result is .
Source : https://www.hackerrank.com/challenges/s10-standard-deviation
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 [] array = new int[size]; | |
| for (int i = 0; i < size; i++) { | |
| array[i] = scan.nextInt(); | |
| } | |
| scan.close(); | |
| System.out.format("%.1f", standardDeviation(array)); | |
| } | |
| public static double getMean(int [] array) { | |
| int sum = 0; | |
| for (int x : array) { | |
| sum += x; | |
| } | |
| return (double) sum / array.length; | |
| } | |
| public static double standardDeviation(int [] array) { | |
| double mean = getMean(array); | |
| double sum = 0; | |
| for (int x : array) { | |
| sum += Math.pow(x - mean, 2); | |
| } | |
| double variance = sum / array.length; | |
| return Math.sqrt(variance); | |
| } | |
| } |
No comments:
Post a Comment