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のFizzBuzz問題(多分これが一番美しいと思います)

Last updated at Posted at 2022-07-11
(1..100).forEach {
  val str = when (Pair(it % 3 == 0, it % 5 == 0)) {
    Pair(false, false) -> it
    Pair(true, false) -> "Fizz"
    Pair(false, true) -> "Buzz"
    else -> "FizzBuzz"
  }
  println(str)
}

KotlinはPair, Tripleでタプルを表現するのでこういう書き方ができます。

もしくは

(1..100).asSequence().map {
  when (Pair(it % 3 == 0, i % 5 == 0)) {
    Pair(false, false) -> it
    Pair(true, false) -> "Fizz"
    Pair(false, true) -> "Buzz"
    else -> "FizzBuzz"
  }
}.forEach(::println)

asSequence()でLazy evaluationが可能となり、1要素毎にprintlnしてくれます。
もしasSequence()を付けずに実装してしまうと、(1..1000000000)のような巨大なループにした場合にEager evaluationな実装となってしまい、1000000000回mapのループを実行した後にまとめてprintlnしようとするためjava.lang.OutOfMemoryErrorとなってしまいます。

to関数を使うとこんな書き方もできます。

(1..100).asSequence().map { i ->
  when ((i % 3 == 0) to (i % 5 == 0)) {
    false to false -> i
    true to false -> "Fizz"
    false to true -> "Buzz"
    else -> "FizzBuzz"
  }
}.forEach(::println)

to関数はPairを作るための関数です。が、ちょっとわかりにくいですね💦

0
0
2

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?