ボーリングのスコア集計プログラム
最近は原点回帰でボーリングのスコア集計プログラムを書いてみたりしているのですが、平鍋さんのblog記事経由でパターンマッチを使う例を(5年遅れで...)見たので、僕もScalaで書いてみました。
object Bowling { def calc(score: List[Int]): Int = { def nextFrame(pins: List[Int], frameCount: Int): Int = { (pins, frameCount) match { case (first :: second :: Nil, 10) => first + second case (first :: second :: third :: Nil, 10) => first + second + third case (10 :: next :: nextOfNext :: more, _) => 10 + next + nextOfNext + nextFrame(next :: nextOfNext :: more, frameCount + 1) case (first :: second :: next :: more, _) if (first + second == 10) => 10 + next + nextFrame(next :: more, frameCount + 1) case (first :: second :: more, _) => first + second + nextFrame(more, frameCount + 1) case _ => throw new IllegalArgumentException } } nextFrame(score, 1) } }
いやー、プログラミングは楽しいですね!