LoginSignup
0
0

More than 5 years have passed since last update.

可変引数Rangeの重複しない整数の個数を求める。

Posted at

可変引数Rangeの重複しない整数の個数を求める。アルゴリズムは<0(n*n)がいいなと思ったけど…


def cover(rs: Range*):Int = ???


assert(cover(0 to 4, 1 to 5) == 6)
assert(cover(0 to 4, 1 to 3) == 5)
assert(cover(0 to 4, 6 to 7) == 7)
assert(cover(0 to 4, 6 to 7, 2 to 6) == 8)

下記以外のがあれば、教えていただきたいです。


def cover(rs: Range*) = rs.map(_.toList).flatMap(x => x).distinct.size

def cover(rs: Range*): Int = {
  @annotation.tailrec
  def helper(xs: List[Range], accu: Int):Int = xs match {
    case Nil => accu
    case r :: Nil => accu + r.size
    case r1 :: r2 :: tail => 
      val nextAccu = accu + r1.size
      if (r2.head > r1.last) helper(r2 :: tail, nextAccu)
      else if (r2.last > r1.last) helper(((r1.last + 1) to r2.last) :: tail, nextAccu)
      else helper(r1 :: tail, accu)
  }
  helper(rs.sortBy(_.start).toList, 0)
}
0
0
1

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