Reputation: 465
I am trying to generate a graph that adds points one by one using a start point and a dictionary
, the dictionary is the form of dictionary<int, int>
before carrying out a path finding algorithm. I would like to populate the dictionary based on two lists of int
values, caveConnections
and connectionWeights
respectively. The point can have more than one connection hence the need for a loop to add the values.
the first int
added to the dictionary is being read line by line from a text file. the second int
value is to be added from a stack
.
I'm unsure on how to achieve this. The output I am trying to achieve is as follows;
Graph g = new Graph();
g.add_vertex(1, new Dictionary<int, int>() {{2, 7}, {3, 8}});
g.add_vertex(2, new Dictionary<int, int>() {{1, 7}, {6, 2}});
g.add_vertex(3, new Dictionary<int, int>() {{1, 8}, {6, 6}, {7, 4}});
g.add_vertex(4, new Dictionary<int, int>() {{6, 8}});
g.add_vertex(5, new Dictionary<int, int>() {{8, 1}});
g.add_vertex(6, new Dictionary<int, int>() {{2, 2}, {3, 6}, {4, 8}, {7, 9}, {8, 3}});
g.add_vertex(7, new Dictionary<int, int>() {{3, 4}, {6, 9}});
g.add_vertex(8, new Dictionary<int, int>() {{5, 1}, {6, 3}});
Text file contents;
4
4 5
5 6 7
1 5 6
2 3 4
3 4
3
Stack built as follows;
Stack<String> connectionStack = new Stack<string>();
List<int> connectionData = new List<int>();
foreach (String s in caveConnections)
{
connectionStack.Push(s);
}
Stack Contents;
2,8,3,2,14,5,7,6,11,2,11,6,14,1
any suggestions would be appreciated.
Upvotes: 1
Views: 1118
Reputation: 34152
string[] lines = File.ReadAllLines("ints.txt");
Graph g = new Graph();
for(int i =0; i< lines.Liength; i++)
{
string[] ints = lines[i].Split(' ');
Dictionary<int, int> dict = new Dictionary<int, int>();
for(int j = 0; j<ints.Length;j++)
if(!dict.ContainsKey(int.Parse(ints[i].Trim())))
dict.Add(int.Parse(ints[i].Trim()), int.Parse(connectionStack.Pop()));
g.add_vertex(i+1, dict);
}
Here of course if the count of stack is less than ints in the text file, you will have an Exception.
Upvotes: 2