-
Notifications
You must be signed in to change notification settings - Fork 0
/
Set.ts
110 lines (93 loc) · 2.38 KB
/
Set.ts
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
import { compare, deepcopy } from "./util";
let print = console.log;
export class Set<T> {
private dataStore: T[];
constructor() {
this.dataStore = new Array<T>();
}
public init(data: T[]) {
for (let e of data) {
this.add(deepcopy(e));
}
}
public contains(elem: T): boolean {
for (let e of this.dataStore) {
if (compare(e, elem)) {
return true;
}
}
return false;
}
private findIndex(elem: T): number {
for (let i = 0; i < this.dataStore.length; i++) {
if (compare(this.dataStore[i], elem)) {
return i;
}
}
return -1;
}
public size(): number {
return this.dataStore.length;
}
public add(elem: T): boolean {
if (this.contains(elem)) {
print("element exist: ", elem);
return false;
}
this.dataStore.push(elem);
return true;
}
public remove(elem: T): boolean {
let index = this.findIndex(elem);
if (index == -1) {
print("Can't find the element in set: ", elem);
return false;
} else {
this.dataStore.splice(index, 1);
return true;
}
}
public union(s: Set<T>): Set<T> {
let tempSet = new Set<T>();
for (let e of this.dataStore) {
tempSet.add(deepcopy(e));
}
let d = s.getSet();
for (let e of d) {
tempSet.add(deepcopy(e));
}
return tempSet;
}
public intersect(s: Set<T>): Set<T> {
let tempSet = new Set<T>();
for (let e of this.dataStore) {
if (s.contains(e)) {
tempSet.add(deepcopy(e));
}
}
return tempSet;
}
public difference(s: Set<T>): Set<T> {
let tempSet = new Set<T>();
for(let e of this.dataStore) {
if(!s.contains(e)) {
tempSet.add(deepcopy(e));
}
}
return tempSet;
}
public subset(s: Set<T>): boolean {
if (this.size() > s.size()) {
return false;
}
for (let e of this.dataStore) {
if (!s.contains(e)) {
return false;
}
}
return true;
}
public getSet(): T[] {
return this.dataStore;
}
}