Last active
July 14, 2016 20:27
-
-
Save Krasnyanskiy/6eac0a3b2ac948079f26fed9aca0032d to your computer and use it in GitHub Desktop.
-scala: Stepic algorithms
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
/** | |
* @author Alexander Krasniansky | |
*/ | |
object PointCover extends App { | |
case class Point(x: Int) | |
case class Segment(start: Int, end: Int) | |
def cover(points: Seq[Point], segmentLength: Int): Seq[Segment] = points match { | |
case x :: _ => | |
def min(points: Seq[Point]) = points sortWith { _.x < _.x } head | |
val mp = min(points) | |
val seg = Segment(mp.x, mp.x + segmentLength) | |
val filtered = points filter { _.x > seg.end } | |
seg +: cover(filtered, segmentLength) | |
case _ => Nil | |
} | |
} |
Tests
val points: Seq[Point] = Seq(
Point(6), Point(8), Point(12),
Point(13), Point(17), Point(18),
Point(22), Point(25)
)
assert(cover(points, 6).size == 3)
assert {
cover(points, 6).contains(Segment(6, 12)) &&
cover(points, 6).contains(Segment(13, 19)) &&
cover(points, 6).contains(Segment(22, 28))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Naive Scala implementation of https://stepic.org/lesson/%D0%92%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5-13238/step/2?course=%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%D1%8B-%D1%82%D0%B5%D0%BE%D1%80%D0%B8%D1%8F-%D0%B8-%D0%BF%D1%80%D0%B0%D0%BA%D1%82%D0%B8%D0%BA%D0%B0-%D0%9C%D0%B5%D1%82%D0%BE%D0%B4%D1%8B&unit=3424