Skip to content

Instantly share code, notes, and snippets.

@allquantor
Created December 28, 2016 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allquantor/76c3cf68706b2572d5de1923e92ea238 to your computer and use it in GitHub Desktop.
Save allquantor/76c3cf68706b2572d5de1923e92ea238 to your computer and use it in GitHub Desktop.
Disjoint set DS
import scala.language._
// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
// Not optimized version
// Supports only integer element sequences starting with 0, where n1 - n2 = -1
object UnionSequence {
def apply(elems: Int*): UnionSequence = {
new UnionSequence(Array(elems:_*) toIndexedSeq)
}
}
case class UnionSequence(elems: IndexedSeq[Int]) {
lazy val count : Int = elems.size
def union(p: Int, q: Int): UnionSequence = {
if (!connected(p, q)) {
val newValue = elems(p)
val oldValue = elems(q)
val ds = Array.ofDim[Int](elems.size)
elems.view.zipWithIndex.map {
case (_, id) if id == oldValue => ds(id) = newValue
case (value, id) => ds(id) = value
}
this.copy(elems = ds toIndexedSeq)
} else this
}
def find(p:Int):Int = elems(p)
def connected(p: Int, q: Int): Boolean = elems(p) == elems(q)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment