Skip to content

Commit 38f53f6

Browse files
committed
Add utilities to import graphs from files. Support two file formats: Edge and Adjacency lists.
1 parent 703bcd5 commit 38f53f6

File tree

1 file changed

+36
-26
lines changed

1 file changed

+36
-26
lines changed

io/io.go

+36-26
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,17 @@ import (
1212
"github.com/jmCodeCraft/go-network/model"
1313
)
1414

15-
func FromAdjacencyListFile(filename string) error {
16-
readFile, err := os.Open(filename)
17-
if err != nil {
18-
return fmt.Errorf("error opening file: %w", err)
19-
}
20-
21-
FromAdjacencyList(readFile)
22-
23-
err = readFile.Close()
24-
if err != nil {
25-
return fmt.Errorf("error closing file: %w", err)
26-
}
27-
return nil
15+
type IGraphFormatReader interface {
16+
Read(reader io.Reader) model.UndirectedGraph
17+
ReadFromFile(filename string) model.UndirectedGraph
18+
AddNodesToGraph(g *model.UndirectedGraph, nodes []model.Node)
2819
}
2920

30-
// FromAdjacencyList reads an adjacency list from a reader.
31-
// The reader should be a CSV file with the following format:
32-
//
33-
// 0,1,2,3
34-
// 1,2
35-
// 2,3
36-
// 3
37-
//
38-
// Each line specifies...
39-
func FromAdjacencyList(reader io.Reader) {
40-
g := model.UndirectedGraph{}
21+
type AdjacencyListReader struct{ IGraphFormatReader } // DONE
22+
type EdgeListReader struct{ IGraphFormatReader } // DONE
23+
24+
func (strategy *IGraphFormatReader) Read(reader io.Reader) model.UndirectedGraph {
25+
ng := model.UndirectedGraph{}
4126

4227
csvReader := csv.NewReader(reader)
4328
lineCount := 0
@@ -47,12 +32,37 @@ func FromAdjacencyList(reader io.Reader) {
4732
if errors.Is(err, io.EOF) {
4833
break
4934
}
50-
return
35+
return nil
5136
}
5237
slog.Info(fmt.Sprintf("read: %+v", read))
53-
g.AddEdgesFromIntEdgeList(model.Node(lineCount), lineToList(read))
38+
nodes := lineToList(read)
39+
IGraphFormatReader.AddNodesToGraph(ng, nodes)
5440
lineCount++
5541
}
42+
return ng
43+
}
44+
45+
func (strategy *IGraphFormatReader) ReadFromFile(filename string) model.UndirectedGraph {
46+
readFile, err := os.Open(filename)
47+
if err != nil {
48+
return fmt.Errorf("error opening file: %w", err)
49+
}
50+
51+
ng := strategy.Read(readFile)
52+
53+
err = readFile.Close()
54+
if err != nil {
55+
return fmt.Errorf("error closing file: %w", err)
56+
}
57+
return ng
58+
}
59+
60+
func (a *AdjacencyListReader) AddNodesToGraph(g *model.UndirectedGraph, nodes []model.Node) {
61+
g.AddEdgesFromIntEdgeList(model.Node(nodes[0]), nodes[1:])
62+
}
63+
64+
func (a *EdgeListReader) AddNodesToGraph(g *model.UndirectedGraph, nodes []model.Node) {
65+
g.AddEdge(model.Edge{nodes[0], nodes[1]})
5666
}
5767

5868
/*

0 commit comments

Comments
 (0)