public IGraph Build() { var lines = File.ReadAllLines(_file); var countData = lines[0].Split(_seperator, StringSplitOptions.RemoveEmptyEntries); var nodeCount = Int32.Parse(countData[0]); var edgeCount = nodeCount*nodeCount; var nodes = new Node[nodeCount + 1]; //+1 since nodes are 1 based var edges = new List<Edge>(edgeCount); var edgeId = 0; foreach (var line in lines.Skip(1)) { var dataitems = line.Split(_seperator, StringSplitOptions.RemoveEmptyEntries); var leftNodeId = Int32.Parse(dataitems[0]); var rightNodeId = Int32.Parse(dataitems[1]); var weight = Int32.Parse(dataitems[2]); var leftNode = nodes[leftNodeId]; if (leftNode == null) { leftNode = new Node(leftNodeId); nodes[leftNodeId] = leftNode; } var rightNode = nodes[rightNodeId]; if (rightNode == null) { rightNode = new Node(rightNodeId); nodes[rightNodeId] = rightNode; } var edge = new Edge(++edgeId, leftNode, rightNode, EdgeDirection.None, weight); edges.Add(edge); } var finalNodes = nodes.Skip(1).ToList(); var finalEdges = edges.OrderBy(e => e.Weight).ToList(); return new Graph(finalNodes, finalEdges); }
public IGraph Build() { var lines = File.ReadAllLines(_file).Skip(1).ToArray(); //skip comment line var countData = lines[0].Split(_seperator, StringSplitOptions.RemoveEmptyEntries); var verticeCount = Int32.Parse(countData[0]); var edgeCount = Int32.Parse(countData[1]); var nodes = new Node[verticeCount + 1]; //since nodes are 1 based var edges = new List<Edge>(edgeCount); var edgeId = 0; foreach (var line in lines.Skip(1)) //skip size line { var data = line.Split(_seperator, StringSplitOptions.RemoveEmptyEntries); var tailLabel = Int32.Parse(data[0]); var headLabel = Int32.Parse(data[1]); var edgeCost = Int32.Parse(data[2]); var tail = nodes[tailLabel]; if (tail == null) { tail = new Node(tailLabel); nodes[tailLabel] = tail; } var head = nodes[headLabel]; if (head == null) { head = new Node(headLabel); nodes[headLabel] = head; } var edge = new Edge(++edgeId, tail, head, EdgeDirection.LeftToRight, edgeCost); edges.Add(edge); nodes[headLabel].IncomingEdges.Add(edge); } var finalNodes = nodes.Skip(1).ToList(); return new Graph(finalNodes, edges); }