Skip to content

Commit 7d1fbb8

Browse files
Reformatted code to match style guide
1 parent 12f54e0 commit 7d1fbb8

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

Graph/Graph.playground/Contents.swift

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,42 @@
11
public struct GraphEdge<T> {
2-
let from: GraphVertex<T>
3-
let to: GraphVertex<T>
4-
let weight: Int
2+
let from: GraphVertex<T>
3+
let to: GraphVertex<T>
4+
let weight: Int
55
}
66

77
public struct GraphVertex<T> {
8-
public var data: T
9-
private var edges: [GraphEdge<T>] // This is a simple adjacency list, rather than matrix
10-
11-
public mutating func connectTo(destinationVertex: GraphVertex<T>, withWeight weight: Int = 0) {
12-
edges.append(GraphEdge(from: self, to: destinationVertex, weight: weight))
13-
}
14-
15-
public mutating func connectBetween(inout otherVertex: GraphVertex<T>, withWeight weight: Int = 0) {
16-
edges.append(GraphEdge(from: self, to: otherVertex, weight: weight))
17-
otherVertex.edges.append(GraphEdge(from: otherVertex, to: self, weight: weight))
18-
}
8+
public var data: T
9+
private var edges: [GraphEdge<T>] = [] // This is a simple adjacency list, rather than matrix
10+
11+
public init(data: T) {
12+
self.data = data
13+
}
14+
15+
// Creates a directed edge self -----> dest
16+
public mutating func connectTo(destinationVertex: GraphVertex<T>, withWeight weight: Int = 0) {
17+
edges.append(GraphEdge(from: self, to: destinationVertex, weight: weight))
18+
}
19+
20+
// Creates an undirected edge by making 2 directed edges: self ----> other, and other ----> self
21+
public mutating func connectBetween(inout otherVertex: GraphVertex<T>, withWeight weight: Int = 0) {
22+
edges.append(GraphEdge(from: self, to: otherVertex, weight: weight))
23+
otherVertex.edges.append(GraphEdge(from: otherVertex, to: self, weight: weight))
24+
}
1925
}
2026

2127

28+
29+
30+
var v1 = GraphVertex(data: 1)
31+
var v2 = GraphVertex(data: 2)
32+
var v3 = GraphVertex(data: 3)
33+
var v4 = GraphVertex(data: 4)
34+
35+
// v1 ---> v2 ---> v3 ---> v4
36+
// ^ |
37+
// | V
38+
// -----------<------------|
39+
v1.connectTo(v2)
40+
v2.connectTo(v3)
41+
v3.connectTo(v4)
42+
v4.connectTo(v1)

0 commit comments

Comments
 (0)