Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Last active August 29, 2015 14:05
Show Gist options
  • Save arialdomartini/a584ec038c89217b31e7 to your computer and use it in GitHub Desktop.
Save arialdomartini/a584ec038c89217b31e7 to your computer and use it in GitHub Desktop.
Range Minimum Query with Segment Trees-like datastructure
object Sample {
def parts(numbers: Vector[Any]): (Vector[Any], Vector[Any]) =
numbers.splitAt(numbers.length / 2)
def buildTree(numbers: Vector[Any]): Vector[Any] =
numbers.length match {
case 1 => numbers
case _ => Vector(buildTree(parts(numbers)._1), buildTree(parts(numbers)._2))
}
def rmq(tree: Vector[Any]): Int =
tree.length match {
case 1 => {
println("Min of" + tree + " is " + tree(0))
tree(0).asInstanceOf[Int]
}
case _ => {
val smallest = Math.min(rmq(tree(0).asInstanceOf[Vector[Any]]), rmq(tree(1).asInstanceOf[Vector[Any]]))
println("Min of" + tree + " is " + smallest)
smallest
}
}
def nums: Vector[Int] = Vector(10, 20, 30)
rmq(buildTree(nums))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment