-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathGraphVertex.ps1
More file actions
135 lines (97 loc) · 2.77 KB
/
GraphVertex.ps1
File metadata and controls
135 lines (97 loc) · 2.77 KB
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
. $PSScriptRoot\..\linked-list\LinkedList.ps1
class GraphVertex {
$value
$edges
GraphVertex() {
$this.DoInit($null)
}
GraphVertex($value) {
$this.DoInit($value)
}
hidden DoInit($value) {
if ($value -eq $null) {
throw 'Graph vertex must have a value'
}
$edgeComparator = {
param($edgeA, $edgeB)
if ($edgeA.getKey() -eq $edgeB.getKey()) {
return 0
}
if ($edgeA.getKey() -lt $edgeB.getKey()) { return -1 }
return 1
}
# Normally you would store string value like vertex name.
# But generally it may be any object as well
$this.value = $value
$this.edges = New-Object LinkedList $edgeComparator
}
[object] addEdge($edge) {
$this.edges.append($edge)
return $this
}
deleteEdge($edge) {
$this.edges.delete($edge)
}
[object] getNeighbors() {
$targetEdges = $this.edges.toArray()
$neighborsConverter = {
param($node)
if ($node.value.startVertex.getKey() -eq $this.getKey()) {
return $node.value.endVertex
}
return $node.value.startVertex
}
# Return either start or end vertex.
# For undirected graphs it is possible that current vertex will be the end one.
return @($targetEdges.ForEach{&$neighborsConverter $_})
}
[object] getEdges() {
return $this.edges.toArray().value
}
[object] getDegree() {
return $this.edges.toArray().Count
}
[bool] hasEdge($requiredEdge) {
$edgeNode = $this.edges.find($null, {
param($edge)
$edge -eq $requiredEdge
})
return !!$edgeNode
}
[object] hasNeighbor($vertex) {
$vertexNode = $this.edges.find($null, {
param($edge)
$edge.startVertex -eq $vertex -or $edge.endVertex -eq $vertex
})
return !!$vertexNode
}
[object] findEdge($vertex) {
$edgeFinder ={
param($edge)
return $edge.startVertex -eq $vertex -Or $edge.endVertex -eq $vertex
};
$targetEdge = $this.edges.find($null, $edgeFinder)
if($targetEdge) {
return $targetEdge.value
}
return $null
}
[object] getKey() {
return $this.value
}
[object] deleteAllEdges() {
foreach ($edge in $this.getEdges()) {
$this.deleteEdge($edge)
}
return $this
}
[string] toString() {
return $this.toString($null)
}
[string] toString($callback) {
if ($callback) {
return &$callback($this.value)
}
return $this.value -join '_'
}
}