Created
May 10, 2015 01:14
-
-
Save songfei1983/7a12bac9481b5e0b9c38 to your computer and use it in GitHub Desktop.
可変引数Rangeの重複しない整数の個数を求める。 ref: http://qiita.com/songfei1983/items/2ea390612bed3b1b40b5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cover(rs: Range*) = rs.map(_.toList).flatMap(x => x).distinct.size | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment