@@ -12,32 +12,17 @@ import (
12
12
"github.com/jmCodeCraft/go-network/model"
13
13
)
14
14
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 )
28
19
}
29
20
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 {}
41
26
42
27
csvReader := csv .NewReader (reader )
43
28
lineCount := 0
@@ -47,12 +32,37 @@ func FromAdjacencyList(reader io.Reader) {
47
32
if errors .Is (err , io .EOF ) {
48
33
break
49
34
}
50
- return
35
+ return nil
51
36
}
52
37
slog .Info (fmt .Sprintf ("read: %+v" , read ))
53
- g .AddEdgesFromIntEdgeList (model .Node (lineCount ), lineToList (read ))
38
+ nodes := lineToList (read )
39
+ IGraphFormatReader .AddNodesToGraph (ng , nodes )
54
40
lineCount ++
55
41
}
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 ]})
56
66
}
57
67
58
68
/*
0 commit comments