본문 바로가기
C#/백준 알고리즘

2022.02.04 [백준] C# 통계학

by ian's coding 2022. 2. 4.
728x90
반응형

 

https://www.acmicpc.net/problem/2108

 

2108번: 통계학

첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.

www.acmicpc.net

 


풀이

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
 
class Program
{
    
    static void Main()
    {
        StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
        StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
        int n = int.Parse(sr.ReadLine());
        int[] num = new int[n];
        for(int i = 0; i < n; i++)
        {
            num[i] = int.Parse(sr.ReadLine());
        }
        Array.Sort(num);
        Console.WriteLine(Avg(n, num));
        Console.WriteLine(MidValue(n, num));
        Console.WriteLine(Mode(n, num));
        Console.WriteLine(Range(n, num));
 
    }
 
 
    static double Avg(int n,int[] num)
    {
        int sum = 0;
        for(int i=0; i < n; i++)
        {
            sum += num[i];
        }
        double avg = Math.Round((double)sum / n);
        if(avg==-0){
            return 0;
        }
        else{
            return avg;
        }
        
    }
 
 
    static int MidValue(int n, int[] num)
    {
        int mid = num[n / 2];
        return mid;
    }
 
 
    static int Mode(int n, int[] num)
    {
        //입력되는 정수의 범위가 절대값 4000이라서 배열의 길이를 8001로 설정
        int[] count = new int[8001];
        List<int> list = new List<int>();
        for(int i=0; i < n; i++)
        {
            count[num[i] + 4000]++;
        }
        //count.Max()를 이용하여 count배열중 가장 큰 값을 뽑아냄.
        int max = count.Max();
        for(int i = 0; i < 8001; i++)
        {
            if (count[i] == max)
            {
                list.Add(i-4000);
            }
        }
        //최빈값이 담긴 list를 오름차순으로 정렬
        list.Sort();
        if (list.Count > 1)
        {
            return list[1];
        }
        else
        {
            return list[0];
        }
    }
 
 
    static int Range(int n, int[] num)
    {
        int range = num[n - 1- num[0];
        return range;
    }
}
 
cs
 

 

 

 

728x90
반응형

댓글