Statistics : calculating mean median mode and standard deviation

/**
 * 
 */
package com.kant.hackerrank.statistics;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

/**
 * @author shaskant
 *
 */
public class Challenge1 {

 static double mean = 0;
 static double median = 0;
 static int mode = Integer.MAX_VALUE;
 static double deviationStd = 0;

 /**
  * @param args
  */
 public static void main(String[] args) {
  @SuppressWarnings("resource")
  Scanner scanner = new Scanner(System.in);
  int inputSize = scanner.nextInt();
  Map<Integer, Integer> store = new TreeMap<Integer, Integer>();
  int count = 0;
  for (int inputC = 0; inputC < inputSize; inputC++) {
   int inputN = scanner.nextInt();
   mean += inputN;

   if (store.containsKey(inputN)) {
    count = store.get(inputN).intValue();
    store.put(inputN, count + 1);
   } else {
    store.put(inputN, 1);
   }
  }
  mean = mean / inputSize;
  System.out.printf("%.1f\n", mean);
  calculateModeAndDeviation(store, inputSize);
  System.out.printf("%.1f\n", median);
  System.out.println(mode);
  System.out.printf("%.1f\n", deviationStd);
 }

 /**
  * 
  * @param store
  */
 private static void calculateModeAndDeviation(Map<Integer, Integer> store,
   int inputSize) {
  Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
  Iterator<Integer> iterator = store.keySet().iterator();
  int maxKey = Integer.MIN_VALUE;
  boolean isOdd = inputSize % 2 != 0;
  int inputC = 0;
  int[] data = new int[inputSize];
  while (iterator.hasNext()) {
   int next = iterator.next().intValue();
   Integer nextVal = store.get(next);
   deviationStd += (double) nextVal * Math.pow(next - mean, 2);
   if (map.containsKey(nextVal)) {
    map.get(nextVal).add(next);
   } else {
    List<Integer> list = new ArrayList<Integer>();
    list.add(next);
    map.put(nextVal, list);
   }
   if (maxKey < nextVal) {
    maxKey = nextVal;
   }
   for (int i = inputC; i < inputC + nextVal; i++)
    data[i] = next;
   inputC += nextVal;
  }

  if (!isOdd) {
   median = (double)(data[inputSize / 2] + data[inputSize / 2 - 1])/2;
  } else {
   median = data[inputSize / 2];
  }

  Iterator<Integer> iterator2 = map.get(maxKey).iterator();
  while (iterator2.hasNext()) {
   int next = iterator2.next().intValue();
   if (mode > next)
    mode = next;
  }

  deviationStd = Math.sqrt(deviationStd / inputSize);

 }
}

Comments