오늘은 2021 Dev Matching 어쩌고 문제로, 아마 모든 프로그래밍 언어 교재의 연습 과제 중 하나인 로또 관련 문제다.
엄청나게 쉬운 단순 구현 문제라서 여러가지 풀이 방법들을 적용해보며 시간 테스트 해보기에 좋아 보인다.
그런데 나는 귀찮아서 반복문, 스트림 두 가지로만 해봤다.
당연히 반복문이 훨씬 빠르다.
1. 반복문 활용
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
|
import java.util.*;
class Solution {
public int[] solution(int[] lottos, int[] win_nums) {
int zero_count = 0;
int same_count = 0;
for (int lotto : lottos) {
if ( lotto == 0 ) zero_count++;
for (int win_num : win_nums) {
if (win_num == lotto) same_count++;
}
}
int sum = zero_count+same_count;
int high_score = 7 - (same_count+zero_count);
int low_score = 7 - same_count;
if (high_score < 1) high_score = 1;
if (high_score > 6) high_score = 6;
if (low_score > 6) low_score = 6;
return new int[]{high_score, low_score};
}
}
|
cs |
직관적이고 빠르다.
사실 더할나위 없이 괜찮은 코드지만, 그래도 심심해서 스트림을 적용해봤다.
2. 스트림
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class Solution {
public int[] solution(int[] lottos, int[] win_nums) {
List<Integer> lottosList = Arrays.stream(lottos).boxed().collect(Collectors.toList());
List<Integer> winNumsList = Arrays.stream(win_nums).boxed().collect(Collectors.toList());
winNumsList.retainAll(lottosList);
int zero_count = 0;
for (int i=0; i<lottosList.size(); i++) {
if (lottosList.get(i) == 0) zero_count++;
}
int highScore = 7 - (winNumsList.size() + zero_count);
int lowScore = 0;
if ( winNumsList.size() == 0 ) { lowScore = 6; }
if ( winNumsList.size() == 0 && zero_count == 0 ) { highScore = 6; }
if ( winNumsList.size() != 0 ) { lowScore = 7 - winNumsList.size(); }
return new int[]{highScore, lowScore};
}
}
|
cs |
그리고 깨달았다. 내가 아직 스트림이 익숙하지 않다는 사실을.. ~~^^^^
retainAll을 사용한 것 외에는 다 기본 반복문으로도 할 수 있는 것들이라 쓸데없는 연산만 더해졌을 뿐
그다지 짧아지지도 않았다..
프로그래머스에서 다른 사람의 정답 보기를 누르면 경이롭게도 오직 stream 하나로 경이롭게 푼 사람의 답안을 확인할 수 있으니 확인해보자
(속도는 10배 정도 느리다고 한다.)
'CS ﹒ Algorithm > Programmers' 카테고리의 다른 글
프로그래머스 문제풀이 (8) 최소직사각형 (0) | 2022.08.26 |
---|---|
프로그래머스 문제풀이 (7) 신고 결과 받기 (0) | 2022.08.24 |
프로그래머스 문제풀이 (6) 성격 유형 검사하기 (0) | 2022.08.19 |
프로그래머스 문제풀이 (5) 키패드 누르기 (0) | 2022.08.17 |
Java 프로그래머스 문제풀이 (4) 없는 숫자 더하기 (0) | 2022.08.11 |