-
Notifications
You must be signed in to change notification settings - Fork 1
/
weighted_undirected_graph.rb
73 lines (59 loc) · 1.28 KB
/
weighted_undirected_graph.rb
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
require 'rgl/adjacency'
class WeightedUnDirectedGraph < RGL::AdjacencyGraph
def initialize(edgelist_class = Set, *other_graphs)
super
@weights = {}
end
def self.[] (*a)
result = new
0.step(a.size-2, 3) { |i| result.add_edge(a[i], a[i+1], a[i+2]) }
result
end
def to_s
(edges.sort_by { |e| e.to_s } +
isolates.sort_by {|n| n.to_s}).map { |e| e.to_s }.join("\n")
end
def isolates
edges.inject(Set.new(vertices)) { |iso, e| iso -= [e.source, e.target] }
end
def add_edge(u, v, w)
super(u,v)
@weights[[u,v]] = w
end
def weight(u, v)
@weights[[u,v]]
end
def remove_edge(u, v)
super
@weights.delete([u,v])
end
def remove_vertex(v)
super
@weights.delete_if { |k, _| k.include?(v) }
end
def edge_class
WeightedUnDirectedEdge
end
def edges
result = []
c = edge_class
each_edge { |u,v| result << c.new(u, v, self) }
result
end
def top_edge
key = @weights.select {|k, v| v == @weights.values.max }.keys.sample
[key, @weights[key]]
end
end
class WeightedUnDirectedEdge < RGL::Edge::UnDirectedEdge
def initialize(a, b, g)
super(a,b)
@graph = g
end
def weight
@graph.weight(source, target)
end
def to_s
"(#{source}-#{weight}-#{target})"
end
end