Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Security.Policy;
- namespace Bandersnatch
- {
- public class Parser
- {
- private static bool GetInt(string line, ref int pos, out int integer)
- {
- int length = line.Length;
- string strInt = "";
- for (int i = 0; i < length; i++)
- {
- if (line[i] == ':')
- {
- pos = i + 1;
- break;
- }
- strInt = strInt + line[i];
- }
- return Int32.TryParse(strInt, out integer);
- }
- private static bool GetMessage(string line, ref int pos, out string message)
- {
- int length = line.Length;
- message = "";
- bool isNeighbours = false;
- for (int i = pos; i < length; i++)
- {
- if (line[i] == ':')
- {
- isNeighbours = true;
- pos = i + 1;
- break;
- }
- message = message + line[i];
- }
- return isNeighbours;
- }
- private static bool GetNeighbours(string line, ref int pos, ref Dictionary<int, string> options)
- {
- int length = line.Length;
- int id = -1;
- string message = "";
- bool error = false;
- while (pos < length)
- {
- if (GetInt(line, ref pos, out id))
- error = true;
- GetMessage(line, ref pos, out message);
- options.Add(id, message);
- }
- return error;
- }
- private static bool ParseLine(string line, out int id, out int type, out string message, ref Dictionary<int, string> options)
- {
- int pos = 0;
- id = -1;
- type = -1;
- message = "";
- bool error = false;
- if (GetInt(line, ref pos, out id))
- error = true;
- else if (GetInt(line, ref pos, out type))
- error = true;
- else if (GetMessage(line, ref pos, out message))
- GetNeighbours(line, ref pos, ref options);
- return error;
- }
- public static Graph CreateGraph(string filename)
- {
- if (!File.Exists(filename))
- return null;
- Graph g = new Graph();
- var lines = File.ReadAllLines(filename);
- bool error = false;
- foreach (string line in lines)
- {
- int id, type;
- string message;
- Dictionary<int, string> options = new Dictionary<int, string>();
- error = ParseLine(line, out id, out type, out message, ref options);
- if (error)
- break;
- Node n = new Node(message, (NodeType)type);
- g.AddNode(id, n);
- g.GetNode(id).neighbours = options;
- }
- return error ? null : g;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement