[프로그래머스] 오픈채팅방

Minsuk Jang·2021년 9월 5일
0

프로그래머스

목록 보기
44/48
post-thumbnail

문제 링크

🤔 풀이 방법

제한 사항 및 입출력을 보고 생각할 수 있는 점은 아래와 같다.

1. result에 유저 아이디에 대한 최신 닉네임을 보여줘야 한다.
2. Enter, Leave는 result가 있지만 Change는 없다.

1. result에 유저 아이디에 대한 최신 닉네임을 보여줘야 한다.

  • 1번 조건을 충족시키기 위해서는 유저 아이디에 해당되는 최신 닉네임을 저장하는 HashMap을 이용한다.

2. Enter, Leave는 result가 있지만 Change는 없다.

  • 2번 조건을 충족시키기 위해서는 본인이 편한 방법으로 구현을 진행하면 된다.
    [필자는 코틀린의 chaining을 이용해서 문제를 해결했다.]

💡 다른 사람 풀이

Sequence와 Collection의 차이점

    fun solution(record: Array<String>): Array<String> {
        val id = HashMap<String, String>()

        return record.map {
            val split = it.split(" ")
            val op = split[0]
            val userId = split[1]

            when(op){
                "Enter", "Change" -> id[userId] = split[2]
                else ->""
            }
            split
        }.asSequence()
            .filter { it[0] != "Change" }
            .map {
                val userId = it[1]

                when (it[0]) {
                    "Enter" -> "${id[userId]}님이 들어왔습니다."
                    "Leave" -> "${id[userId]}님이 나갔습니다."
                    else -> throw IllegalArgumentException()
                }

            }.toList().toTypedArray()
    }

체이닝을 이용한다는 점은 비슷했으나 가장 큰 차이점으로 중간에 있는 asSequence를 이용한다는 점이다.

👉 소스 코드

class Solution {
    fun solution(record: Array<String>): Array<String> {
        val id = HashMap<String, String>()

        return record.map {
            it.split(" ")
        }.map {
            val op = it[0]
            val userId = it[1]

            if (op != "Leave")
                id[userId] = it[2]

            when (op) {
                "Enter" -> "$op $userId"
                "Leave" -> "$op $userId"
                else -> null
            }
        }.mapNotNull {
            it?.split(" ")
        }.map {
            val op = it[0]
            val userId = it[1]

            when (op) {
                "Enter" -> "${id[userId]}님이 들어왔습니다."
                "Leave" -> "${id[userId]}님이 나갔습니다."
                else -> ""
            }
        }.toTypedArray()

    }
}
profile
Positive Thinking

0개의 댓글