-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethodIntersect.go
63 lines (54 loc) · 1.26 KB
/
methodIntersect.go
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
package stringset
import "sync"
// Intersect restituisce un nuovo *StringSet con solo gli elementi presenti
// in entrambi s e other: s ∩ other
func (s *StringSet) Intersect(other *StringSet) *StringSet {
var wg sync.WaitGroup
var slen, otherlen int
wg.Add(2)
go func() {
defer wg.Done()
s.lock.Lock()
slen = len(s.m)
s.lock.Unlock()
}()
go func() {
defer wg.Done()
other.lock.Lock()
otherlen = len(other.m)
other.lock.Unlock()
}()
wg.Wait()
var intersection *StringSet
switch {
case slen >= otherlen:
intersection = createIntersect(otherlen, other, s)
default:
intersection = createIntersect(slen, s, other)
}
return intersection
}
func createIntersect(smallerlen int, smaller, greater *StringSet) *StringSet {
ret := &StringSet{
m: make(map[string]struct{}, smallerlen),
}
// copia il set meno numeroso in ret
smaller.lock.Lock()
for str := range smaller.m {
ret.m[str] = struct{}{}
}
smaller.lock.Unlock()
greater.lock.Lock()
defer greater.lock.Unlock()
for element := range ret.m {
// se l'elemento in smaller esiste anche in greater prosegue
if _, exists := greater.m[element]; exists {
continue
}
// altrimenti lo rimuove da ret.
ret.lock.Lock()
delete(ret.m, element)
ret.lock.Unlock()
}
return ret
}