Skip to content

Instantly share code, notes, and snippets.

@Krasnyanskiy
Last active July 14, 2016 20:27
Show Gist options
  • Save Krasnyanskiy/6eac0a3b2ac948079f26fed9aca0032d to your computer and use it in GitHub Desktop.
Save Krasnyanskiy/6eac0a3b2ac948079f26fed9aca0032d to your computer and use it in GitHub Desktop.
-scala: Stepic algorithms
/**
* @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
}
}
@Krasnyanskiy
Copy link
Author

Krasnyanskiy commented Jul 9, 2016

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