summaryrefslogtreecommitdiffstats
path: root/IO/GraphFile.cs
diff options
context:
space:
mode:
Diffstat (limited to 'IO/GraphFile.cs')
-rw-r--r--IO/GraphFile.cs54
1 files changed, 54 insertions, 0 deletions
diff --git a/IO/GraphFile.cs b/IO/GraphFile.cs
new file mode 100644
index 0000000..9298e4b
--- /dev/null
+++ b/IO/GraphFile.cs
@@ -0,0 +1,54 @@
+using System.Text.RegularExpressions;
+using Graph.Interfaces;
+
+namespace Graph.IO
+{
+ public static class GraphFile
+ {
+ public static Graph<double> Read(IFileReader reader)
+ {
+ string[] lines = reader.Lines;
+ Graph<double> graph = new Graph<double>();
+
+ foreach (string line in reader.Lines)
+ {
+ // split string into vertex id and the edges
+ string[] parts = line.Split(" ", 2);
+
+ // parse vertex id
+ int vertex = int.Parse(parts[0]);
+
+ // parse edges, matches pairs of number two at a time, i.e. "num num"
+ Match match = Regex.Match(parts[1], @"[^ ]+ [^ ]+");
+ while (match.Success)
+ {
+ // for each match, split the "vertex weight" pair
+ string[] edge = match.Value.Split(" ", 2);
+
+ // add edge to graph (vertex1, vertex2, weight)
+ graph.AddEdge(new Edge<double>(
+ vertex,
+ int.Parse(edge[0]),
+ double.Parse(edge[1])
+ ));
+
+ // iterate match
+ match = match.NextMatch();
+ }
+ }
+
+ return graph;
+ }
+
+ public static void Print(Graph<double> graph, IFileWriter writer)
+ {
+ string outstring = "";
+ graph.Vertices.ForEach(v =>
+ {
+ outstring += $"\n{v.Id}";
+ v.Edges.ForEach(e => outstring += $" {e.V} {e.Weight.ToString("F1")}");
+ });
+ writer.WriteAllText(outstring.Trim());
+ }
+ }
+} \ No newline at end of file