-
Notifications
You must be signed in to change notification settings - Fork 312
/
Copy pathHand.kt
34 lines (29 loc) · 1013 Bytes
/
Hand.kt
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
package blackjack.domain
@JvmInline
value class Hand(val cards: MutableList<Card> = mutableListOf()) {
fun add(card: Card) = cards.add(card)
fun getCardCount() = cards.size
fun getBestScore(): Score {
val scoreSums = mutableSetOf<Score>()
calculateScoreSums(cards.toList(), 0, Score.from(0), scoreSums)
return when (scoreSums.minBy { it.value }.value <= Rule.BLACKJACK_SCORE) {
true -> {
scoreSums
.filter { it.value <= Rule.BLACKJACK_SCORE }
.maxBy { it.value }
}
false -> {
scoreSums.minBy { it.value }
}
}
}
private fun calculateScoreSums(cards: List<Card>, index: Int, sum: Score, sums: MutableSet<Score>) {
if (index == cards.size) {
sums.add(sum)
return
}
cards[index].getPossibleScoreSums(sum).forEach {
calculateScoreSums(cards, index + 1, it, sums)
}
}
}