-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package db | ||
|
||
import "sort" | ||
|
||
// UndirectedGraph represents undirected graph | ||
type UndirectedGraph struct { | ||
matrix map[string]map[string]bool | ||
} | ||
|
||
// NewUndirectedGraph returns a new UndirectedGraph instance | ||
func NewUndirectedGraph() *UndirectedGraph { | ||
return &UndirectedGraph{matrix: map[string]map[string]bool{}} | ||
} | ||
|
||
// PutSymmetric put value to symmetric matrix | ||
func (g *UndirectedGraph) PutSymmetric(row string, col string, value bool) { | ||
g.initRow(row) | ||
g.initRow(col) | ||
|
||
g.matrix[row][col] = value | ||
g.matrix[col][row] = value | ||
} | ||
|
||
func (g *UndirectedGraph) initRow(row string) { | ||
_, ok := g.matrix[row] | ||
|
||
if ok { | ||
return | ||
} | ||
|
||
g.matrix[row] = map[string]bool{} | ||
} | ||
|
||
// GetRowColumns returns columns of row | ||
func (g *UndirectedGraph) GetRowColumns(row string) []string { | ||
var columns []string | ||
|
||
g.initRow(row) | ||
|
||
for k, v := range g.matrix[row] { | ||
if v { | ||
columns = append(columns, k) | ||
} | ||
} | ||
|
||
sort.Strings(columns) | ||
return columns | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package db | ||
|
||
import ( | ||
"github.com/stretchr/testify/assert" | ||
"testing" | ||
) | ||
|
||
func TestUndirectedGraph_PutSymmetric(t *testing.T) { | ||
g := NewUndirectedGraph() | ||
g.PutSymmetric("a", "b", true) | ||
|
||
assert.Equal(t, true, g.matrix["a"]["b"]) | ||
assert.Equal(t, true, g.matrix["b"]["a"]) | ||
} | ||
|
||
func TestUndirectedGraph_GetRowColumns(t *testing.T) { | ||
g := NewUndirectedGraph() | ||
g.PutSymmetric("a", "b", true) | ||
g.PutSymmetric("a", "c", false) | ||
g.PutSymmetric("e", "a", true) | ||
g.PutSymmetric("d", "a", true) | ||
g.PutSymmetric("c", "d", true) | ||
|
||
got1 := g.GetRowColumns("a") | ||
assert.Equal(t, []string{"b", "d", "e"}, got1) | ||
|
||
got2 := g.GetRowColumns("unknown") | ||
assert.Empty(t, got2) | ||
} |