diff options
author | Toby Vincent <tobyv13@gmail.com> | 2021-03-25 00:39:48 +0000 |
---|---|---|
committer | Toby Vincent <tobyv13@gmail.com> | 2021-03-25 00:39:48 +0000 |
commit | 4293a0cd2fa3a9a5ba050e463f0b8473c5aba232 (patch) | |
tree | 3f57cf62baba6c67d0eab8baa0c9ef1b63d2f335 /IO |
refactored project layout
Diffstat (limited to 'IO')
-rw-r--r-- | IO/FileReader.cs | 15 | ||||
-rw-r--r-- | IO/FileWriter.cs | 22 | ||||
-rw-r--r-- | IO/GraphFile.cs | 54 |
3 files changed, 91 insertions, 0 deletions
diff --git a/IO/FileReader.cs b/IO/FileReader.cs new file mode 100644 index 0000000..12aa12b --- /dev/null +++ b/IO/FileReader.cs @@ -0,0 +1,15 @@ +using System.IO; +using Graph.Interfaces; + +namespace Graph.IO +{ + public class FileReader : IFileReader + { + public string[] Lines { get; } + + public FileReader(string filename) + { + Lines = File.ReadAllLines(filename); + } + } +} diff --git a/IO/FileWriter.cs b/IO/FileWriter.cs new file mode 100644 index 0000000..c423f52 --- /dev/null +++ b/IO/FileWriter.cs @@ -0,0 +1,22 @@ +using System; +using System.IO; +using Graph.Interfaces; + +namespace Graph.IO +{ + public class FileWriter : IFileWriter + { + string FilePath { get; } + + public FileWriter(string filePath) + { + FilePath = filePath; + } + + public void WriteAllText(string content) + { + Console.WriteLine(content); + File.WriteAllText(FilePath, content); + } + } +}
\ No newline at end of file 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 |