class Director[T] (val parents : scala.collection.immutable.HashMap[T,Elem[T]]) {
def Add(x : T) : Director[T] = parents.get(x) match {
case None => new Director[T](parents + ((x,new Elem[T](x,0))))
case Some(p) => this
}
def Find(x : T) : (Director[T],Elem[T]) = parents.get(x) match{
case None => (Add(x),new Elem[T](x,0))
case Some(p) if p.x.equals(x) => (this,p)
case Some(p) =>
val (_,np) = Find(p.x)
val npar = parents + ((p.x,np))
val ndir = new Director[T](npar)
(ndir,np)
}
def Union(x : T,y : T) : Director[T] = {
val (timedir,rx) = Find(x)
val (ndir,ry) = timedir.Find(y)
if (rx.depth < ry.depth) {
val npar = ndir.parents + ((rx.x,ry))
new Director[T](npar)
} else {
val npar = ndir.parents + ((ry.x,rx))
if (rx.depth == ry.depth) {
val nnpar = npar + ((x,new Elem[T](rx.x,rx.depth + 1)))
new Director[T](nnpar)
} else new Director[T](npar)
}
}
def Print() = {
val it = parents.iterator
while (it.hasNext) {
val (x,px) = it.next()
println("Elem : " + x + " Parent : " + px.x + " Depth " + px.depth )
}
}
}
class Elem[T] (val x : T, val depth : Int){
}
import scala.collection.immutable.HashMap
/**
* Created by manda_000 on 20.05.2015.
*/
object lab4 {
def main(args : Array[String]) : Unit = {
var dir = new Director[String](new HashMap[String,Elem[String]])
dir = dir.Add("Hello")
dir = dir.Add("Hell")
dir = dir.Union("Hello","Hell")
dir.Print()
}
}