I am trying to parse a text file that is of the form:
A B 2
A G 6
A C 99
...
B C 7
B E 2
B G 99
Now, these represent “nodes” and the “costs” between them to implement a shortest path algorithm.
I have decided to create a Node class that has 2 instance variables, a name and an array of hashes that are the neighboring nodes and costs to get there.
I am trying to figure out how to parse the file into a series of node objects from each group of lines.
The cost of 99 mean the nodes aren’t connected.
First of all, you should also have a Graph class to manage the nodes and edges. Then something like this should get you started:
The graph,
g, tracks the nodes it has sofind_or_create_nodecan return the node if it already exists or create it and cache it if not. Theadd_edgemethod would connectn1andn2with an edge of weightwt.to_i.Your shortest path algorithm would, presumably, be a method call on the graph objects.