Last active
August 29, 2015 14:05
-
-
Save arialdomartini/a584ec038c89217b31e7 to your computer and use it in GitHub Desktop.
Range Minimum Query with Segment Trees-like datastructure
This file contains 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
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