Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.IO;
  5. using System.Security.Policy;
  6.  
  7. namespace Bandersnatch
  8. {
  9. public class Parser
  10. {
  11. private static bool GetInt(string line, ref int pos, out int integer)
  12. {
  13. int length = line.Length;
  14. string strInt = "";
  15.  
  16. for (int i = 0; i < length; i++)
  17. {
  18. if (line[i] == ':')
  19. {
  20. pos = i + 1;
  21. break;
  22. }
  23. strInt = strInt + line[i];
  24. }
  25. return Int32.TryParse(strInt, out integer);
  26. }
  27.  
  28. private static bool GetMessage(string line, ref int pos, out string message)
  29. {
  30. int length = line.Length;
  31. message = "";
  32. bool isNeighbours = false;
  33.  
  34. for (int i = pos; i < length; i++)
  35. {
  36. if (line[i] == ':')
  37. {
  38. isNeighbours = true;
  39. pos = i + 1;
  40. break;
  41. }
  42. message = message + line[i];
  43. }
  44. return isNeighbours;
  45. }
  46.  
  47. private static bool GetNeighbours(string line, ref int pos, ref Dictionary<int, string> options)
  48. {
  49. int length = line.Length;
  50. int id = -1;
  51. string message = "";
  52. bool error = false;
  53.  
  54. while (pos < length)
  55. {
  56. if (GetInt(line, ref pos, out id))
  57. error = true;
  58. GetMessage(line, ref pos, out message);
  59. options.Add(id, message);
  60. }
  61. return error;
  62. }
  63.  
  64. private static bool ParseLine(string line, out int id, out int type, out string message, ref Dictionary<int, string> options)
  65. {
  66. int pos = 0;
  67. id = -1;
  68. type = -1;
  69. message = "";
  70. bool error = false;
  71.  
  72. if (GetInt(line, ref pos, out id))
  73. error = true;
  74. else if (GetInt(line, ref pos, out type))
  75. error = true;
  76. else if (GetMessage(line, ref pos, out message))
  77. GetNeighbours(line, ref pos, ref options);
  78. return error;
  79. }
  80.  
  81. public static Graph CreateGraph(string filename)
  82. {
  83. if (!File.Exists(filename))
  84. return null;
  85.  
  86. Graph g = new Graph();
  87. var lines = File.ReadAllLines(filename);
  88. bool error = false;
  89.  
  90. foreach (string line in lines)
  91. {
  92. int id, type;
  93. string message;
  94. Dictionary<int, string> options = new Dictionary<int, string>();
  95. error = ParseLine(line, out id, out type, out message, ref options);
  96. if (error)
  97. break;
  98. Node n = new Node(message, (NodeType)type);
  99. g.AddNode(id, n);
  100. g.GetNode(id).neighbours = options;
  101. }
  102. return error ? null : g;
  103. }
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement