Skip to content

Commit

Permalink
Add Graph.LinkUnique()
Browse files Browse the repository at this point in the history
  • Loading branch information
ScarletTanager committed Mar 21, 2023
1 parent 4a327ae commit 9d75bf0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
3 changes: 3 additions & 0 deletions graph/graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ type Graph interface {
Link(int, int) error
// LinkBoth creates a bidirectionally navigable edge linking the source and target vertices
LinkBoth(int, int)
// LinkUnique only creates an edge between the vertices if one does not
// already exist.
LinkUnique(int, int)
// Path returns either an ordered slice of vertices (if a path exists from the source to the target)
// or nil
Path(int, int) ([]*Vertex, error)
Expand Down
34 changes: 24 additions & 10 deletions graph/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,34 @@ import (

func (a AdjacencyList) Link(source, target int) error {
svp := a[source]
if svp.edgeIndices == nil {
svp.edgeIndices = make([]int, 0)
}

// It is entirely allowable to have multiple edges linking the same two
// vertices, but our current model does not provide any good way to distinguish
// between edges connecting the same vertices, so the lack of a uniqueness test
// here is a bug, not really a feature. We'll want to make edges actual "things"
// later on.
svp.edgeIndices = append(svp.edgeIndices, target)
link(svp, target)

return nil
}

func (a AdjacencyList) LinkBoth(source, target int) {
}

func (a AdjacencyList) LinkUnique(source, target int) {
svp, _ := a.AtIndex(source)
for _, ei := range svp.edgeIndices {
if ei == target {
// Link is there, stop
return
}
}

link(svp, target)
}

func link(svp *Vertex, target int) {
if svp.edgeIndices == nil {
svp.edgeIndices = make([]int, 0)
}

svp.edgeIndices = append(svp.edgeIndices, target)
return
}

const (
Expand Down Expand Up @@ -160,7 +173,8 @@ func (a AdjacencyList) WithAttribute(attrName string, attrVal interface{}) []*Ve
return vertices
}

// New creates a new graph.
// New creates a new graph. You must supply a non-nil slice of vertices (which can be empty, although
// that feels like a weird thing to do).
func New(vertices []Vertex) (Graph, error) {
var l AdjacencyList

Expand Down

0 comments on commit 9d75bf0

Please sign in to comment.