-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
edge.go
136 lines (115 loc) · 2.36 KB
/
edge.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package graphman
import (
"fmt"
"sort"
"strings"
)
//
// Edge
//
type Edge struct {
src *Vertex
dst *Vertex
deleted bool // temporary variable used by gc()
Attrs
}
type EdgeCostFN func(e *Edge) int64
func newEdge(src, dst *Vertex, attrs ...Attrs) *Edge {
var a Attrs
if len(attrs) > 0 {
a = attrs[0]
} else {
a = make(map[string]interface{})
}
return &Edge{
src: src,
dst: dst,
Attrs: a,
}
}
func (e Edge) Dst() *Vertex { return e.dst }
func (e Edge) Src() *Vertex { return e.src }
func (e *Edge) Vertices() Vertices {
return Vertices{e.src, e.dst}
}
func (e *Edge) String() string {
ret := fmt.Sprintf("(%s,%s)", e.src.id, e.dst.id)
if !e.Attrs.IsEmpty() {
ret += fmt.Sprintf("[%s]", e.Attrs)
}
return ret
}
func (e *Edge) HasVertex(id string) bool {
return e.src.id == id || e.dst.id == id
}
func (e *Edge) OtherVertex(id string) *Vertex {
if e.src.id == id {
return e.dst
}
if e.dst.id == id {
return e.src
}
return nil
}
//
// Edges
//
type Edges []*Edge
func (e Edges) filtered() Edges {
filtered := Edges{}
for _, edge := range e {
if !edge.deleted {
filtered = append(filtered, edge)
}
}
return filtered
}
func (e Edges) String() string {
items := []string{}
for _, edge := range e {
items = append(items, edge.String())
}
return fmt.Sprintf("{%s}", strings.Join(items, ","))
}
func (e Edges) Equals(other Edges) bool {
tmp := map[*Edge]int{}
for _, edge := range e {
tmp[edge]++
}
for _, edge := range other {
tmp[edge]--
}
for _, v := range tmp {
if v != 0 {
return false
}
}
return true
}
// AllCombinations returns the different combinations of Edges in a group of Edges
//
// Adapted from https://github.com/mxschmitt/golang-combinations
func (e Edges) AllCombinations() EdgesCombinations {
combinations := EdgesCombinations{}
length := uint(len(e))
for combinationBits := 1; combinationBits < (1 << length); combinationBits++ {
var combination Edges
for object := uint(0); object < length; object++ {
if (combinationBits>>object)&1 == 1 {
combination = append(combination, e[object])
}
}
combinations = append(combinations, combination)
}
return combinations
}
//
// EdgesCombinations
//
type EdgesCombinations []Edges
func (ec EdgesCombinations) LongestToShortest() EdgesCombinations {
sort.Slice(ec, func(i, j int) bool {
return len(ec[i]) > len(ec[j])
})
return ec
}