코딩테스트/백준

[Java] 백준 - 4344번 평균은 넘겠지

배똥회장 2022. 8. 3. 11:48
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

4344번: 평균은 넘겠지

대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.

www.acmicpc.net

 

 

 

 

 

▽ Stream으로 계산하는 코드 ▽ 

import java.io.*;
import java.util.Arrays;
public class Main {	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		
		for (int t = 0; t < n; t++) {
			//Stream을 이용하여 String[]을 int[]로 변환하는 방법
			int[] list = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
			
			int num = list[0];
			int[] score = Arrays.copyOfRange(list, 1, list.length);
			
			//Stream을 이용하여 int배열 내 숫자의 총 합을 내는 방법
			double avg = Arrays.stream(score).sum() / num;

			//Stream을 이용하여 int배열 내 숫자들 중 조건에 맞는 숫자들 개수 구하는 방법
			double count = Arrays.stream(score).filter(number -> number > avg).count();

			bw.write(String.format("%.3f", count / num * 100) + "%\n");
		}
		bw.flush();
		bw.close();
	}
}

 

▽ for문으로 계산하는 코드 

import java.io.*;
public class Main {	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		
		for (int t = 0; t < n; t++) {
			String[] temp = br.readLine().split(" ");

			int num = Integer.parseInt(temp[0]);
			int[] score = new int[num];
			
			int sum = 0;
			for (int i = 1; i < temp.length; i++) {
				score[i-1] = Integer.parseInt(temp[i]);
				sum += score[i-1];
			}
			
			double avg = sum / num;
			int count = 0;
			for (int i = 0; i < score.length; i++) {
				if (score[i] > avg) count++;
			}
			
			bw.write(String.format("%.3f", (double) count / num * 100) + "%\n");
		}
		bw.flush();
		bw.close();
	}
}

 

코드 문제 결과 메모리 시간 코드 길이
for문 4344 맞았습니다!! 15880 176 829
Stream 4344 맞았습니다!! 16296 192 836

 

 

 

 

 

 

728x90