summaryrefslogtreecommitdiffstats
path: root/IO/GraphFile.cs
blob: 9298e4ba8cc63cd190c5e2d68a06e3726ca4661b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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());
        }
    }
}