1
1
//: Playground - noun: a place where people can play
2
2
3
- public class UnionFindDS < T: Hashable > {
3
+ public struct UnionFind < T: Hashable > {
4
4
5
5
private var index = [ T: Int] ( )
6
6
private var parent = [ Int] ( )
7
7
private var size = [ Int] ( )
8
8
9
9
10
- public func addSetWithElement( element: T ) {
10
+ public mutating func addSetWithElement( element: T ) {
11
11
index [ element] = parent. count
12
12
parent. append ( parent. count)
13
13
size. append ( 1 )
14
14
}
15
15
16
- private func findSetByIndexOfElement( index: Int ) -> Int {
16
+ private mutating func findSetByIndexOfElement( index: Int ) -> Int {
17
17
if parent [ index] == index {
18
18
return index
19
19
} else {
@@ -22,12 +22,12 @@ public class UnionFindDS<T: Hashable> {
22
22
}
23
23
}
24
24
25
- public func findSetOfElement( element: T ) -> Int {
25
+ public mutating func findSetOfElement( element: T ) -> Int {
26
26
let indexOfElement = index [ element] !
27
27
return findSetByIndexOfElement ( indexOfElement)
28
28
}
29
29
30
- public func unionSetsWithElement( firstElement: T , andSecondElement secondElement: T ) {
30
+ public mutating func unionSetsWithElement( firstElement: T , andSecondElement secondElement: T ) {
31
31
let firstSet = findSetOfElement ( firstElement)
32
32
let secondSet = findSetOfElement ( secondElement)
33
33
if ( firstSet != secondSet) {
@@ -43,7 +43,7 @@ public class UnionFindDS<T: Hashable> {
43
43
}
44
44
45
45
46
- let dsu = UnionFindDS < Int > ( )
46
+ var dsu = UnionFind < Int > ( )
47
47
48
48
for i in 1 ... 10 {
49
49
dsu. addSetWithElement ( i)
@@ -74,7 +74,7 @@ print(dsu.findSetOfElement(8) == dsu.findSetOfElement(9))
74
74
print ( dsu. findSetOfElement ( 4 ) == dsu. findSetOfElement ( 3 ) )
75
75
76
76
77
- let dsuForStrings = UnionFindDS < String > ( )
77
+ var dsuForStrings = UnionFind < String > ( )
78
78
let words = [ " all " , " border " , " boy " , " afternoon " , " amazing " , " awesome " , " best " ]
79
79
80
80
dsuForStrings. addSetWithElement ( " a " )
0 commit comments