Algorithm/Kotlin

[알고리즘] 오픈채팅방

y0ngha 2021. 10. 30. 22:44

프로그래머스 Level 2 문제

https://programmers.co.kr/learn/courses/30/lessons/42888

 

코딩테스트 연습 - 오픈채팅방

오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오

programmers.co.kr

 

위 문제의 풀이 핵심은 User별 Nickname 관리를 진행하는게 핵심이다.

UserID를 Key로 잡고 Nickname을 Value로 잡아서 Map을 활용해 문제를 해결했다.

Change와, Leave 후 Enter 모두 User DATA에서 UserID가 있는지 확인하고 있다면 바꿔주고, User가 입력한 Commands를 모두 기록한 뒤 나중에 포맷에 맞게 바꿔주면 문제는 끝난다.

 

사실 굉장히 비효율적으로 문제를 푼거같긴한데.. 다른 좋은 방법이 생각나질 않는다.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
val users: MutableMap<String, String> = mutableMapOf()
 
fun main() {
    val usersConvRecords: MutableList<MutableMap<String, String>> = mutableListOf()
    val records: Array<String> = arrayOf("Enter uid1234 Muzi",
        "Enter uid4567 Prodo",
        "Leave uid1234",
        "Enter uid1234 Prodo",
        "Change uid4567 Ryan")
    val outputRecords: MutableList<String> = mutableListOf()
    // userid, nickname (최신화)
 
 
    records.forEach { record ->
        val splits = record.split(" ")
//        println(splits)
        val command = splits[0]
        val userId = splits[1]
        var args = ""
        if (splits.size == 3)
            args = splits[2]
 
        if (users[userId].isNullOrEmpty()) {
            users[userId] = args
        } else {
            if(command == "Enter") {
                if(users[userId] != args) {
                    users[userId] = args
                }
            }
        }
 
        if (command == "Change") {
            users[userId] = args
        }
 
        val userRecord: MutableMap<String, String> = mutableMapOf()
        userRecord[userId] = command
        usersConvRecords.add(userRecord)
    }
    usersConvRecords.forEach {
        it.forEach { (key, value) ->
            if (value != "Change")
                outputRecords.add(convRecord(key, value))
        }
    }
 
    println(outputRecords)
}
 
fun convRecord(userId: String, command: String): String {
    return "${users[userId]}님이 ${if (command == "Enter") "들어왔습니다." else "나갔습니다."}"
}
 
cs