-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileReader.cs
More file actions
81 lines (66 loc) · 2.47 KB
/
Copy pathFileReader.cs
File metadata and controls
81 lines (66 loc) · 2.47 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
namespace genetic_algorithm_graph_partitioning;
/// <summary>
/// Simple class to read a graph from a file.
/// </summary>
public class FileReader
{
/// <summary>
/// Reads a graph from a file and returns a list of vertices.
/// </summary>
/// <param name="filePath">The path to the file.</param>
/// <returns>List of vertices</returns>//
public static List<Vertex> ReadGraphFromFile(string filePath)
{
List<Vertex> vertices = new List<Vertex>();
try
{
using (StreamReader? sr = new StreamReader(filePath))
{
while (!sr.EndOfStream)
{
string? line = sr.ReadLine();
if (line == null)
{
throw new Exception("Something went wrong with reading the file. Exiting..");
}
string[] parts = line.Split(' ');
int index = 0;
while (parts?[index] == "")
{
index++;
}
if (parts == null)
{
throw new Exception("Something went wrong with reading the file. Exiting..");
}
int id = int.Parse(parts[index]);
// Extracting coordinates
string[] coordinates = parts[index + 1].Trim('(', ')').Split(',');
double x = double.Parse(coordinates[0]);
double y = double.Parse(coordinates[1]);
index += 2;
while (parts[index] == "")
{
index++;
}
int connections = int.Parse(parts[index]);
index += 2;
// Extracting connected vertices
int[] conns = new int[connections];
for (int i = 0; i < connections; i++)
{
// connectedVertices.Add(int.Parse(parts[index + i]));
conns[i] = int.Parse(parts[index + i]);
}
Vertex vertex = new Vertex(id, x, y, conns);
vertices.Add(vertex);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while reading the file: {ex.Message}");
}
return vertices;
}
}