SW Test/Programmers

[Programmers] Lv1.์‹ ๊ณ  ๊ฒฐ๊ณผ ๋ฐ›๊ธฐ(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 7. 23. 00:35
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/92334?language=kotlin

 

์˜ˆ์‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/92334?language=kotlin

 

 

 

ํ’€์ด

  • ํ•ด๋‹น ๋ฌธ์ œ๋Š” map, set ๋“ฑ์˜ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ž˜ ์กฐํ•ฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
  • ๋จผ์ €, id_report_set์— id์— ํ•˜๋‚˜์˜ set์„ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” map์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
  • ์ดํ›„ report์˜ ํ•˜๋‚˜์”ฉ ํƒ์ƒ‰ํ•˜๋ฉด์„œ id_report_set์— ๊ฐ’์„ ์„ธํŒ…ํ•ฉ๋‹ˆ๋‹ค. ์ค‘๋ณต๋œ ์‚ฌ๋žŒ์€ ์ž๋™์œผ๋กœ ์ œ๊ฑฐ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.
  • reported_count์—๋Š” id ๋งˆ๋‹ค ์‹ ๊ณ ๋ฐ›์€ ํšŸ์ˆ˜๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ํ•ด๋‹น ๊ฐ’์€ id_report_set์„ ํƒ์ƒ‰ํ•˜์—ฌ id๊ฐ€ ์‹ ๊ณ ํ•œ ์‚ฌ๋žŒ๋“ค์„ ๋‹ด์€ value ๊ฐ’์œผ๋กœ ํ•˜๋‚˜์”ฉ ํšŸ์ˆ˜๋ฅผ ์ฆ๊ฐ€์‹œํ‚ต๋‹ˆ๋‹ค.
  • ๋งˆ์ง€๋ง‰์œผ๋กœ id_list๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉด์„œ id๊ฐ€ ์‹ ๊ณ ํ•œ ์‚ฌ๋žŒ๋“ค ์ค‘ ๊ฒฐ๊ณผ ๋ฉ”์ผ์„ ๋ฐ›์€ ์‚ฌ๋žŒ๋“ค์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.
  fun solution(id_list: Array<String>, report: Array<String>, k: Int): IntArray {
        var answer = IntArray(id_list.size)
        val id_report_set = mutableMapOf<String, Set<String>>().apply {
            id_list.forEach {
                put(it, setOf<String>())
            }
        }

        report.forEach {
            val str = it.split(" ")
            id_report_set.put(str[0], id_report_set.get(str[0])!! + setOf(str[1]))
        }

        val reported_count = mutableMapOf<String, Int>()
        for (elem in id_report_set) {
            val idset = elem.value
            idset.forEach {
                reported_count.put(it, (reported_count.get(it) ?: 0) + 1)
            }
        }

        id_list.forEachIndexed { index, elem ->
            val idset = id_report_set.get(id_list.get(index))!!
            answer[index] = idset.filter { reported_count.get(it)!! >= k }.size
        }

        return answer
    }

 

 

  • ์œ„์ฒ˜๋Ÿผ ํ’€ ์ˆ˜๋„ ์žˆ์ง€๋งŒ kotlin์˜ ๋‹ค์–‘ํ•œ ํ•จ์ˆ˜๋“ค์„ ์ž˜ ์•Œ๊ณ  ์žˆ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ฉ”์†Œ๋“œ ์ฒด์ด๋‹๋งŒ ์‚ฌ์šฉํ•˜์—ฌ ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!! ๐Ÿ˜Ž
  • distinct, groupBy, flatten ๋ชจ๋ฅด๋Š” ๋ฉ”์†Œ๋“œ๋“ค์ด ๋งŽ์•˜๊ธฐ์— ์ž˜ ๊ธฐ๋กํ•ด ๋‘ก์‹œ๋‹ค~~ 
fun solution2(id_list: Array<String>, report: Array<String>, k: Int): IntArray =
            report.distinct().map { it.split(" ") }
                    .groupBy { it[1] }
                    .map { it.value }
                    .filter { it.size >= k }
                    .flatten()
                    .groupBy { it[0] }
                    .run { id_list.map { get(it)?.size ?: 0 }.toIntArray() }

 

 

 

์ฐธ๊ณ 

 

groupBy - Kotlin Programming Language

 

kotlinlang.org

 

distinct - Kotlin Programming Language

 

kotlinlang.org

 

flatten - Kotlin Programming Language

 

kotlinlang.org

 

๋ฐ˜์‘ํ˜•