Skip to content

Instantly share code, notes, and snippets.

@yosemitebandit
Created December 18, 2014 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yosemitebandit/818bac265aa12866e874 to your computer and use it in GitHub Desktop.
Save yosemitebandit/818bac265aa12866e874 to your computer and use it in GitHub Desktop.
some of the early Ch2 exercises from think complexity; now here: github.com/yosemitebandit/think-complexity
package graph
type Vertex struct {
Label string
}
type Edge struct {
Start Vertex
End Vertex
}
type Graph struct {
vertices []Vertex
edges []Edge
connections map[Vertex]Vertex
}
func (g *Graph) Add_vertex(v Vertex) {
g.vertices = append(g.vertices, v)
}
// Connect two vertices.
// Init the connections map if it is empty.
func (g *Graph) connect(v1, v2 Vertex) {
if g.connections == nil {
g.connections = make(map[Vertex]Vertex)
}
g.connections[v1] = v2
g.connections[v2] = v1
}
func (g *Graph) Add_edge(e Edge) {
g.connect(e.Start, e.End)
g.edges = append(g.edges, e)
}
package graph
import "testing"
func TestAddVertex(t *testing.T) {
v1 := Vertex{"v1"}
g := new(Graph)
g.Add_vertex(v1)
if g.vertices[0] != v1 {
t.Error("expected v1, got ", g.vertices[0])
}
}
func TestConnect(t *testing.T) {
v1 := Vertex{"v1"}
v2 := Vertex{"v2"}
v3 := Vertex{"v3"}
v4 := Vertex{"v4"}
g := new(Graph)
g.connect(v1, v2)
g.connect(v3, v4)
if g.connections[v1] != v2 {
t.Error("v1 -/-> v2")
}
if g.connections[v2] != v1 {
t.Error("v2 -/-> v1")
}
if g.connections[v3] != v4 {
t.Error("v3 -/-> v4")
}
if g.connections[v4] != v3 {
t.Error("v4 -/-> v3")
}
}
func TestAddEdge(t *testing.T) {
v1 := Vertex{"v1"}
v2 := Vertex{"v2"}
e1 := Edge{v1, v2}
g := new(Graph)
g.Add_edge(e1)
if g.edges[0] != e1 {
t.Error("expected e1, got ", g.edges[0])
}
if g.connections[v1] != v2 {
t.Error("v1 -/-> v2")
}
if g.connections[v2] != v1 {
t.Error("v2 -/-> v1")
}
}
package main
import (
"fmt"
"github.com/yosemitebandit/thinkcomplexity/ch2/graph"
)
func main() {
v1, v2, v3, v4, v5 := graph.Vertex{"v1"}, graph.Vertex{"v2"}, graph.Vertex{"v3"}, graph.Vertex{"v4"}, graph.Vertex{"v5"}
e1, e2 := graph.Edge{v1, v2}, graph.Edge{v3, v4}
g := new(graph.Graph)
for _, v := range []graph.Vertex{v1, v2, v3, v4, v5} {
g.Add_vertex(v)
}
for _, e := range []graph.Edge{e1, e2} {
g.Add_edge(e)
}
fmt.Println(g)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment