0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Kotlin】カードを配る

Last updated at Posted at 2021-09-12

これが10分でできない人は自分がかなりプログラミングができないというつらい事実を認識しましょう。」を Kotlin でやってみた。

解答

fun deal(playerCount: Int, cards: String): List<String> {
    // 各プレイヤーの手札
    val hands = List(playerCount) { StringBuilder() }

    cards.windowed(playerCount, playerCount) // 余りを無視するため、chunked ではなく windowed を使う。
        .forEach { chunk -> // ここから各プレイヤーに1枚ずつ渡す。
            hands.forEachIndexed { index, hand ->
                val card = chunk[index]
                hand.append(card)
            }
        }

    return hands.map { it.toString() }
}

別解(関数型プログラミング的解答)

ちょっと分かりにくい。

fun deal(playerCount: Int, cards: String): List<String> =
    cards
        .dropLast(cards.length % playerCount) // 余りを除く。
        .withIndex()
        .groupBy(
            { it.index % playerCount }, // カードを誰(※)に配るか。※プレイヤーのインデックス(Int型)
            { it.value } // カード(Char型)
        )
        .map { it.value.joinToString("") }
        // ↑ではカードの枚数が人数未満だった場合にはリストが空になる。
        // そのため↓で人数分の空文字列を持つリストに差し替える。
        .takeIf { it.isNotEmpty() }
        ?: List(playerCount) { "" }

/以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?