본문 바로가기

programming/algorithm 공부

[hackerrank] s10-basic-statistics Day 0 - Mean, Median, and Mode

1. 문제 정보

 

 

 1) 링크 : https://www.hackerrank.com/challenges/s10-basic-statistics/problem

 

Day 0: Mean, Median, and Mode | HackerRank

Compute the mean, median, mode, and standard deviation.

www.hackerrank.com

 2) 혹시 링크가 바뀔경우 문제 파일 PDF : 

s10-basic-statistics-English.pdf
0.27MB

2. 설명

 

 1) 요구사항

    - 정의된 Mean 값을 출력하되 소수점 한자리수까지만 출력한다.

    - 정의된 Median 값을 출력하되 소수점 한자리수까지만 출력한다.

    - 정의된 Mode 값을 출력한다.

    - 입력값은 특정 범위내 자연수이다.

 

 2) 입력값

    입력값은 두가지이다. N과 int 배열의 값이 하나씩 입력된다.

    - 모두 자연수이며 {N | 10 <= N <= 2500}, int 배열 X의 원소들은 {x | 0 < x < 100000, x X}

    - 배열 X의 원소 갯수는 N = n(X).

 

 3) 알고리즘 설명

    고등학생때 통계/분석을 하기 위해 배우는 기초적인 수학적 지식을 설명하고 이를 구현하는 내용이다.

    Mean이라는 값은 우리가 잘 알고 있는 Average (평균)이다.

    Median은 중앙값 또는 중간값이라 하여 자료를 정렬했을때 가운데 있게 되는 데이터를 의미한다. 대게 Raw 한 값으로서 평균에 근사할 확률이 높은 데이터라 할 수 있다. (물론 표준편차가 큰 경우 Median이 데이터 가운데 가장 평균에 근사할 확률은 떨어진다.)

    Mode는 빈도수가 가장 많은 값들중 최솟값이다. 본래 Mode는 Raw한 통계 자료에서 가장 빈번히 발생하는 데이터 모두를 가리키나 여기서는 출력을 위해 최솟값만 요구하고 있다. (사실 Mode는 유의미와 무의미한 데이터를 구분하는 한가지 방법이기도 하다.)

 

 

전체 소스 : 

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String tmp = sc.nextLine();
        int N = Integer.parseInt(tmp);
        int[] x = new int[N];
        int sum = 0, mode = Integer.MAX_VALUE;
        HashMap<Integer,Integer> frecuenceMap = new HashMap<Integer, Integer>();
        for(int inx=0; inx<N; inx++)
        {
            x[inx] = sc.nextInt();

            if(!frecuenceMap.containsKey(x[inx]))
                frecuenceMap.put(x[inx], 1);
            else
                frecuenceMap.put(x[inx], frecuenceMap.get(x[inx])+1);
            sum += x[inx];
        }
        double mean = sum *1.0 / N;
        Arrays.sort(x);
        double leftMiddle = N%2==0 ? x[N/2-1] : x[N/2]*1.0/2;
        double rightMiddle = N%2==0 ? x[N/2] : x[N/2]*1.0/2;

        int frecuenceMax = 0;
        for(int inx=0; inx<N; inx++)
        {
            if(frecuenceMap.get(x[inx]) < frecuenceMax) continue;
            if(frecuenceMap.get(x[inx]) > frecuenceMax)
            {
                frecuenceMax = frecuenceMap.get(x[inx]);
                mode = Integer.MAX_VALUE;
            }
            if(mode > x[inx]) mode = x[inx];
        }

        System.out.printf("%.1f\n",mean);
        System.out.println((leftMiddle+rightMiddle+0.0)/2);
        System.out.println(mode);
    }
}

 

 

반응형