LoginSignup
2
2

More than 5 years have passed since last update.

整数配列の連続区間をグループ化するやつやってみた

Last updated at Posted at 2016-01-08

整数配列の連続区間をグループ化するアレをScalaでやってみた

を読んで面白そうだったので自分も書いてみた。

元の記事の方ではワンラインで書いてるけど、自分は普通(?)に書いてみた。

object Main extends App {
  val sample = Seq(1, 2, 3, 4, 5, 8, 9, 10, 13, 14, 20, 22)

  def group_mini(seq: Seq[Int], s: Int, e: Int): Seq[(Int, Int)] = seq match {
    case Nil => Seq((s, e))
    case h+:t =>
      if(h == e+1)
        group_mini(t, s, h)
      else
        (s, e) +: group_mini(t, h, h)
  }

  def group(seq: Seq[Int]) = seq match {
    case Nil => Nil
    case h+:t => group_mini(t, h, h)
  }

  println(group(sample))
}

実行結果

List((1,5), (8,10), (13,14), (20,20), (22,22))

追記

文字列の出力までやるの忘れてたけど、書かなくてもいいかな。

2
2
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
2
2