forked from gazolla/Kotlin-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderedSet.kt
116 lines (92 loc) · 2.59 KB
/
OrderedSet.kt
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* Created by gazollajunior on 08/04/16.
*/
fun main() {
println("\nOriginal set:")
val names = mutableListOf("Demetrius")
val nameSet = OrderedSet(names)
println(nameSet)
val n1 = "Adam"
println("\nAdding $n1 to the list:")
nameSet.insert(n1)
println(nameSet)
val n2 = "Tim"
println("\nAdding $n2 to the list:")
nameSet.insert(n2)
println(nameSet)
val n3 = "Zack"
println("\nAdding $n3 to the list:")
nameSet.insert(n3)
println(nameSet)
val n4 = "Zack"
println("\nTry Add $n4 again to the list:")
nameSet.insert(n4)
println(nameSet)
nameSet.remove(n2)
println("\nRemoving $n2 from the list:")
println(nameSet)
nameSet.remove(n4)
println("\nRemoving $n4 from the list:")
println(nameSet)
nameSet.remove(n1)
println("\nRemoving $n1 from the list:")
println(nameSet)
}
class OrderedSet<T : Comparable<T>>(list: MutableList<T>) {
var items: MutableList<T> = list
fun insert(element: T) {
if (exists(element)) {
return
}
for (i in 0..<this.items.count()) {
if (this.items[i] > element) {
this.items.add(i, element)
return
}
}
this.items.add(element)
}
/**
* Use binarySearch algorithm to find the position for the new element in array
*/
fun findElementPosition(element: T): Int? {
var rangeStart = 0
var rangeEnd = this.items.count()
while (rangeStart < rangeEnd) {
val midIndex = rangeStart + (rangeEnd - rangeStart) / 2
if (this.items[midIndex] == element) {
return midIndex
} else if (this.items[midIndex] < element) {
rangeStart = midIndex + 1
} else {
rangeEnd = midIndex
}
}
return null
}
override fun toString(): String = this.items.toString()
fun isEmpty(): Boolean = this.items.isEmpty()
fun exists(element: T): Boolean = findElementPosition(element) != null
fun count(): Int = this.items.count()
fun remove(element: T) {
val position = findElementPosition(element)
if (position != null) {
this.items.removeAt(position)
}
}
fun removeAll() = this.items.removeAll(this.items)
fun max(): T? {
return if (count() != 0) {
this.items[count() - 1]
} else {
null
}
}
fun min(): T? {
return if (count() != 0) {
this.items[0]
} else {
null
}
}
}