본문 바로가기

Development/CodingTest

[Array] Softeer level 3 성적 평균 Java 풀이 (%.2f는 자동 반올림!!)

https://softeer.ai/practice/6294

 

Softeer - 현대자동차그룹 SW인재확보플랫폼

 

softeer.ai

풀이법

  • 점수의 누적합을 저장하는 배열을 선언
  • 구간의 끝에 해당하는 배열의 인덱스 값에서, 구간의 시작 - 1에 해당하는 배열의 인덱스를 빼고 평균을 냄
  • 처음엔 Math.round로 반올림을 해야하나 싶었는데 printf("%.2f", 값) 을 하면 알아서 소수 둘째자리 까지 출력하고, 셋째자리에서 반올림을 해준다..

예를 들어

5 3
10 50 20 70 100
1 3

의 경우 배열에

구간 0 1 2 3
누적합 0 10 60 80

이렇게 저장이 되고, 

1부터 3까지 구간은 

구간의 끝인 3에 값 80에서 구간의 첫 시작 - 1, 즉 0의 인덱스 값 0을 뺀 다음

구간 수 만큼 나눠주면 (80 - 0 / 3)이 된다.

코드

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(in.readLine());
        int numOfStudent = Integer.parseInt(st.nextToken());
        int numOfRange = Integer.parseInt(st.nextToken());

        int[] scoreCollection = new int[numOfStudent + 1];
        st = new StringTokenizer(in.readLine());
        for(int i = 1; i <= numOfStudent; i++){
            scoreCollection[i] = scoreCollection[i - 1] + Integer.parseInt(st.nextToken());
        }

        for(int j = 0; j < numOfRange; j++){
            st = new StringTokenizer(in.readLine());
            int first = Integer.parseInt(st.nextToken());
            int last = Integer.parseInt(st.nextToken());
            double avg = (double)(scoreCollection[last] - scoreCollection[first - 1]) / (last - first + 1);
            System.out.printf("%.2f\n", (avg * 100) / 100);
        }
        
    }
}