Skip to content

Instantly share code, notes, and snippets.

@loosechainsaw
Created December 10, 2013 12:31
Show Gist options
  • Save loosechainsaw/7889898 to your computer and use it in GitHub Desktop.
Save loosechainsaw/7889898 to your computer and use it in GitHub Desktop.
Scala Quick Find and Quick Union implementations
import scala.annotation.tailrec
object Main extends App {
def QuickFindExample() {
var qu = QuickFind(10)
qu.union(1, 6)
qu.union(2, 6)
qu.union(2, 7)
println("Connected (2,6): " + qu.connected(2, 6))
println("Connected (2,7): " + qu.connected(2, 7))
println("Connected (1,6): " + qu.connected(1, 6))
println("Connected (1,8): " + qu.connected(1,8))
}
def QuickUnionExample() {
var qu = QuickUnion(10)
qu.union(1, 6)
qu.union(2, 6)
qu.union(2, 7)
println("Connected (2,6): " + qu.connected(2, 6))
println("Connected (2,7): " + qu.connected(2, 7))
println("Connected (1,6): " + qu.connected(1, 6))
println("Connected (1,8): " + qu.connected(1,8))
}
QuickFindExample()
QuickUnionExample()
}
trait UnionFind {
def union(destination: Int, source: Int): Unit;
def connected(a: Int, b: Int): Boolean;
}
case class QuickFind(val size: Int) extends UnionFind {
private val items = new Array[Int](size)
items.indices.foreach(x => {
items(x) = x
})
def union(destination: Int, source: Int): Unit = {
val itematdest = items(destination)
val itematsource = items(source)
if (itematdest == itematsource)
return
items.zipWithIndex.foreach(x => {
if (x._1 == itematsource)
items(x._2) = itematdest
})
}
def connected(a: Int, b: Int): Boolean = ((items(a)).equals(items(b)))
}
case class QuickUnion(val size: Int) extends UnionFind {
private val items = new Array[Int](size)
items.indices.foreach(x => {
items(x) = x
})
def union(destination: Int, source: Int): Unit = {
val itematdest = items(destination)
val itematsource = items(source)
val rootdest = root(itematdest)
val rootsource = root(itematsource)
if (rootdest != rootsource)
items(rootsource) = rootdest
}
@tailrec
private def root(component: Int) : Int = {
val item = items(component)
if(item == component)
component
else
root(item)
}
def connected(a: Int, b: Int): Boolean = ((root(items(a))).equals(root(items(b))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment