-
Exercism - Scrabble Score (With.Kotlin)문제풀이/Exercism 2019. 7. 30. 14:35반응형
[문제]
Given a word, compute the scrabble score for that word.
Letter Values
You'll need these:
Letter : Value
A, E, I, O, U, L, N, R, S, T : 1
D, G : 2
B, C, M, P : 3
F, H, V, W, Y : 4
K : 5
J, X : 8
Q, Z : 10
Examples
"cabbage" should be scored as worth 14 points:
- 3 points for C
- 1 point for A, twice
- 3 points for B, twice
- 2 points for G
- 1 point for E
And to total:
- 3 + 2*1 + 2*3 + 2 + 1
- = 3 + 2 + 6 + 3
- = 5 + 9
- = 14
Extensions
- You can play a double or a triple letter.
- You can play a double or a triple word.
[Solution1]
object ScrabbleScore { fun scoreWord(input: String): Int { var point = 0 val listOfPointOne = listOf('A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T') val listOfPointTwo = listOf('D', 'G') val listOfPointThree = listOf('B', 'C', 'M', 'P') val listOfPointFour = listOf('F', 'H', 'V', 'W', 'Y') val listOfPointFive = listOf('K') val listOfPointEight = listOf('J', 'X') val listOfPointTen = listOf('Q', 'Z') input.toCharArray().map { when (it.toUpperCase()) { in listOfPointOne -> point += 1 in listOfPointTwo -> point += 2 in listOfPointThree -> point += 3 in listOfPointFour -> point += 4 in listOfPointFive -> point += 5 in listOfPointEight -> point += 8 in listOfPointTen -> point += 10 } } return point } }
해당 리스트를 포인트별로 구분하여 포인트의 합을 구함
[Solution2]
object ScrabbleScore { fun scoreWord(input: String): Int = input.toCharArray().map { checkCharPoint(it) }.sum() private fun checkCharPoint(c : Char): Int{ return when (c.toUpperCase()) { 'A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T' -> 1 'D', 'G' -> 2 'B', 'C', 'M', 'P' -> 3 'F', 'H', 'V', 'W', 'Y' -> 4 'K' -> 5 'J', 'X' -> 8 'Q', 'Z' -> 10 else -> throw Exception("Unknow Char : $c") } } }
point 라는 변수를 사용 하지 않고 sum()을 사용해서 합을 도출하도록 변경
[Solution3]
object ScrabbleScore { fun scoreWord(input: String): Int = input.sumBy { charPoint(it) } private fun charPoint(c : Char): Int{ return when (c.toUpperCase()) { 'A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T' -> 1 'D', 'G' -> 2 'B', 'C', 'M', 'P' -> 3 'F', 'H', 'V', 'W', 'Y' -> 4 'K' -> 5 'J', 'X' -> 8 'Q', 'Z' -> 10 else -> throw Exception("Unknow Char : $c") } } }
코드를 최적화 , map 과 sum 을 합친 sumBy 를 사용 하여 처리 하도록 수정
반응형'문제풀이 > Exercism' 카테고리의 다른 글
Exercism - Luhn(with.Kotlin) (0) 2019.08.19 Exercism - Acronym(with.Kotlin) (0) 2019.08.19 Exercism - Perfect Numbers(with.Kotlin) (0) 2019.08.17 Exercism - Difference Of Squares(with.Kotlin) (0) 2019.08.06 Exercism - Space Age (With.Kotlin) (0) 2019.07.26 Exercism - Gigasecond(With.Kotlin) (0) 2019.07.23 Exercism - Leap(With.Kotlin) (0) 2019.07.22 Exercism - Hamming(With.Kotlin) (0) 2019.07.21