Programming/Algorithm & Data Structure
[Swift] 프로그래머스 2022 KAKAO BLIND RECRUITMENT신고 결과 받기
guswlsdk
2022. 6. 27. 14:25
반응형
코딩테스트 연습 - 신고 결과 받기
문제 설명 신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다. 각 유저는 한 번에 한 명의
programmers.co.kr
오랜만에 해서 감이 많이 떨어진 것 같다...
처음에 성공했을 때는 코드가 가독도 힘들도 지저분한 느낌이 들었다.
다른 사람들의 풀이를 보고 딕셔너리를 충분히 이용하여 코드 수를 줄이고 가독성을 늘릴 수 있었다.
import Foundation
func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] {
var reportedNameCount = [String : Int]() // id별 신고 누적 횟수
var reportList = [[String]]() // id 별 신고한 id 리스트, [0]는 신고자, 이후엔 신고한 id 리스트이다.
// id별 신고 누적 횟수 2차원 배열로 초기화
for i in id_list{
reportedNameCount[i] = 0
}
for i in id_list{
reportList.append([i])
}
for i in report{
let temp = i.split(separator: " ").map {String($0)}
let reporter = temp[0] // 신고한 사람
let reportee = temp[1] // 신고된 사람
for index in 0..<reportList.count{
if reportList[index][0] == reporter{
if !reportList[index].contains(reportee){ // 신고자는 같은 대상을 한 번만 신고할 수 있음
reportList[index].append(reportee)
reportedNameCount[reportee] = reportedNameCount[reportee]!+1
break
}
}
if index == reportList.count{
reportList.append([reporter,reportee])
reportedNameCount[reportee] = reportedNameCount[reportee]!+1
}
}
}
var result = [Int]()
for list in reportList {
var count = 0
for index in 1..<list.count{
if reportedNameCount[list[index]]! >= k{
count+=1
}
}
result.append(count)
}
return result
}
import Foundation
func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] {
var reportedNameCount = [String : Int]() // id별 신고 누적 횟수
var reportListDict = [String : [String]]() // id 별 신고한 id 리스트, [0]는 신고자, 이후엔 신고한 id 리스트이다.
// id별 신고 누적 횟수 2차원 배열로 초기화
for i in id_list{
reportedNameCount[i] = 0
reportListDict[i] = []
}
for i in Array(Set(report)){
let temp = i.split(separator: " ").map {String($0)}
let reporter = temp[0] // 신고한 사람
let reportee = temp[1] // 신고된 사람
reportedNameCount[reportee]! += 1
reportListDict[reporter]?.append(reportee)
}
var result = [Int]()
for reporter in id_list{
var count = 0
for i in reportListDict[reporter]!{
if reportedNameCount[i]! >= k {
count += 1
}
}
result.append(count)
}
return result
}
반응형