class Director val parents scala collection immutable HashMap Elem def

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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()
}
}