신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다.
- 각 유저는 한 번에 한 명의 유저를 신고할 수 있습니다.
- 신고 횟수에 제한은 없습니다. 서로 다른 유저를 계속해서 신고할 수 있습니다.
- 한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다.
- k번 이상 신고된 유저는 게시판 이용이 정지되며, 해당 유저를 신고한 모든 유저에게 정지 사실을 메일로 발송합니다.
- 유저가 신고한 모든 내용을 취합하여 마지막에 한꺼번에 게시판 이용 정지를 시키면서 정지 메일을 발송합니다.
다음은 전체 유저 목록이 ["muzi", "frodo", "apeach", "neo"]이고, k = 2(즉, 2번 이상 신고당하면 이용 정지)인 경우의 예시입니다.
유저 ID | 유저가 신고한 ID | 설명 |
---|---|---|
"muzi" | "frodo" | "muzi"가 "frodo"를 신고했습니다. |
"apeach" | "frodo" | "apeach"가 "frodo"를 신고했습니다. |
"frodo" | "neo" | "frodo"가 "neo"를 신고했습니다. |
"muzi" | "neo" | "muzi"가 "neo"를 신고했습니다. |
"apeach" | "muzi" | "apeach"가 "muzi"를 신고했습니다. |
각 유저별로 신고당한 횟수는 다음과 같습니다.
유저 ID | 신고당한 횟수 |
---|---|
"muzi" | 1 |
"frodo" | 2 |
"apeach" | 0 |
"neo" | 2 |
위 예시에서는 2번 이상 신고당한 "frodo"와 "neo"의 게시판 이용이 정지됩니다. 이때, 각 유저별로 신고한 아이디와 정지된 아이디를 정리하면 다음과 같습니다.
유저 ID | 유저가 신고한 ID | 정지된 ID |
---|---|---|
"muzi" | ["frodo", "neo"] | ["frodo", "neo"] |
"frodo" | ["neo"] | ["neo"] |
"apeach" | ["muzi", "frodo"] | ["frodo"] |
"neo" | 없음 | 없음 |
따라서 "muzi"는 처리 결과 메일을 2회, "frodo"와 "apeach"는 각각 처리 결과 메일을 1회 받게 됩니다.
이용자의 ID가 담긴 문자열 배열 id_list, 각 이용자가 신고한 이용자의 ID 정보가 담긴 문자열 배열 report, 정지 기준이 되는 신고 횟수 k가 매개변수로 주어질 때, 각 유저별로 처리 결과 메일을 받은 횟수를 배열에 담아 return 하도록 solution 함수를 완성해주세요.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
//유저 신고 기록
HashMap<String,Set<String>> reportList = new HashMap<>();
//유저 신고 횟수
HashMap<String,Integer> mailCnt = new HashMap<>();
for(int i=0;i<id_list.length;i++) {
reportList.put(id_list[i], new HashSet<>());
mailCnt.put(id_list[i], 0);
}
//신고 기록
for(int i=0;i<report.length;i++) {
int n = report[i].indexOf(" ");
String reportUser = report[i].substring(0,n);
String reportedUser = report[i].substring(n+1);
reportList.get(reportedUser).add(reportUser);
}
//신고 횟수
for(int i=0;i<id_list.length;i++) {
if(reportList.get(id_list[i]).size()>=k) {
for(int j=0;j<id_list.length;j++) {
if(reportList.get(id_list[i]).contains(id_list[j])==true) {
mailCnt.put(id_list[j], mailCnt.get(id_list[j])+1);
}
}
}
}
//정리
for(int i=0;i<id_list.length;i++) {
answer[i] = mailCnt.get(id_list[i]).intValue();
}
return answer;
}
}
유저 아이디가 담긴 id_list를 reportList, mailCnt의 key값으로 넣어준다.
// 신고 기록
report의 문자열을 공백 기준으로 잘라 reportUser(신고한 유저) / reportedUser(신고당한 유저) 구분
reportList.get(reportedUser) 신고당한 유저를 key로 갖는 값을 찾아 .add(reportUser) 신고한 유저를 value에 추가한다.
// 신고 횟수
value.size()를 이용해 해당 유저를 신고한 유저의 수를 구한다.
만약 k보다 크거나 같은 경우, mailCnt에서 신고한 유저와 매치되는 key를 찾아 value에 1을 더해준다.
// 정리
mailCnt.get(id_list[i]).intValue();를 사용해 id_list 순대로 메일 횟수를 정렬해준다.
HashMap에는 primitive type인 int 자료형을 넣지 못하기 때문에 intValue()를 사용해 Interger → int로 변환한다.
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
List<String> list = Arrays.stream(report).distinct().collect(Collectors.toList());
HashMap<String, Integer> count = new HashMap<>();
for (String s : list) {
String target = s.split(" ")[1];
count.put(target, count.getOrDefault(target, 0) + 1);
}
return Arrays.stream(id_list).map(_user -> {
final String user = _user;
List<String> reportList = list.stream().filter(s -> s.startsWith(user + " ")).collect(Collectors.toList());
return reportList.stream().filter(s -> count.getOrDefault(s.split(" ")[1], 0) >= k).count();
}).mapToInt(Long::intValue).toArray();
}
}
Arrays.stream(report).distinct()를 이용해 배열의 중복 값을 바로 제거했다. 이후 .collect(Collectors.toList())로 Stream을 List로 변환
split(" ")[1]로 공백으로 문자열을 나눠 target을 신고당한 유저로 초기화
HashMap count에 key로 target을 삽입해 getOrDefault(target,0)+1 해당 키의 값이 존재하면 값+1, 존재하지 않으면 default로 0을 설정해 +1
하나씩 천천히 보자면
(여러 블로그들을 참고하여 풀이했는데, 스트림은 미숙하기 때문에 틀린 부분이 있을 수도 있다.)
final String user = _user;
List<String> reportList = list.stream(id_list).filter(s -> s.startWith(user + " ")).collect(Collectors.toList());
return reportList.stream().filter(s -> count.getOrDefault(s.split(" ")[1], 0) >= k).count();
Arrays.stream(id_list).map(생략).mapToInt(Long::intValue).toArray()
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
ArrayList<User> users = new ArrayList<>();
HashMap<String,Integer> suspendedList = new HashMap<>(); //<이름>
HashMap<String,Integer> idIdx = new HashMap<String,Integer>(); // <이름, 해당 이름의 User 클래스 idx>
int idx = 0;
for(String name : id_list) {
idIdx.put(name,idx++);
users.add(new User(name));
}
for(String re : report){
String[] str = re.split(" ");
//suspendedCount.put(str[0], suspendedCount.getOrDefault(str[0],0)+1);
users.get( idIdx.get(str[0])).reportList.add(str[1]);
users.get( idIdx.get(str[1])).reportedList.add(str[0]);
}
for(User user : users){
if(user.reportedList.size() >= k)
suspendedList.put(user.name,1);
}
for(User user : users){
for(String nameReport : user.reportList){
if(suspendedList.get(nameReport) != null){
answer[idIdx.get(user.name)]++;
}
}
}
return answer;
}
}
class User{
String name;
HashSet<String> reportList;
HashSet<String> reportedList;
public User(String name){
this.name = name;
reportList = new HashSet<>();
reportedList = new HashSet<>();
}
}
컬렉션으로 유저 객체를 생성하여 작업한 객체지향적 코드
스트림 (Stream)
Stream은 컬렉션, 배열 등의 저장 요소를 하나씩 참조하며 반복적으로 처리할 수 있도록 하는 기능이다. 람다식을 적용한다.
https://school.programmers.co.kr/learn/courses/30/lessons/92334
https://dpdpwl.tistory.com/81
https://kedric-me.tistory.com/entry/JAVA-%EB%9E%8C%EB%8B%A4%EC%8B%9D-map-filter-reduce-collect
https://jeong-pro.tistory.com/165