Advertisement
Guest User

Untitled

a guest
Jul 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. public class Edge
  2. {
  3. public readonly Node From;
  4. public readonly Node To;
  5. public Edge(Node first, Node second)
  6. {
  7. this.From = first;
  8. this.To = second;
  9. }
  10. public bool IsIncident(Node node)
  11. {
  12. return From == node || To == node;
  13. }
  14. public Node OtherNode(Node node)
  15. {
  16. if (!IsIncident(node)) throw new ArgumentException();
  17. if (From == node) return To;
  18. return From;
  19. }
  20. }
  21.  
  22. public class Node
  23. {
  24. readonly List<Edge> edges = new List<Edge>();
  25. public readonly int NodeNumber;
  26.  
  27. public Node(int number)
  28. {
  29. NodeNumber = number;
  30. }
  31.  
  32. public IEnumerable<Node> IncidentNodes
  33. {
  34. get
  35. {
  36. return edges.Select(z => z.OtherNode(this));
  37. }
  38. }
  39. public IEnumerable<Edge> IncidentEdges
  40. {
  41. get
  42. {
  43. foreach (var e in edges) yield return e;
  44. }
  45. }
  46. public static Edge Connect(Node node1, Node node2, Graph graph)
  47. {
  48. if (!graph.Nodes.Contains(node1) || !graph.Nodes.Contains(node2)) throw new ArgumentException();
  49. var edge = new Edge(node1, node2);
  50. node1.edges.Add(edge);
  51. node2.edges.Add(edge);
  52. return edge;
  53. }
  54. public static void Disconnect(Edge edge)
  55. {
  56. edge.From.edges.Remove(edge);
  57. edge.To.edges.Remove(edge);
  58. }
  59. }
  60.  
  61. public class Graph
  62. {
  63. private Node[] nodes;
  64.  
  65. public Graph(int nodesCount)
  66. {
  67. nodes = Enumerable.Range(0, nodesCount).Select(z => new Node(z)).ToArray();
  68. }
  69.  
  70. public int Length { get { return nodes.Length; } }
  71.  
  72. public Node this[int index] { get { return nodes[index]; } }
  73.  
  74. public IEnumerable<Node> Nodes
  75. {
  76. get
  77. {
  78. foreach (var node in nodes) yield return node;
  79. }
  80. }
  81.  
  82. public void Connect(int index1, int index2)
  83. {
  84. Node.Connect(nodes[index1], nodes[index2], this);
  85. }
  86.  
  87. public void Delete(Edge edge)
  88. {
  89. Node.Disconnect(edge);
  90. }
  91.  
  92. public IEnumerable<Edge> Edges
  93. {
  94. get
  95. {
  96. return nodes.SelectMany(z => z.IncidentEdges).Distinct();
  97. }
  98. }
  99.  
  100. public static Graph MakeGraph(params int[] incidentNodes)
  101. {
  102. var graph = new Graph(incidentNodes.Max() + 1);
  103. for (int i = 0; i < incidentNodes.Length - 1; i += 2)
  104. graph.Connect(incidentNodes[i], incidentNodes[i + 1]);
  105. return graph;
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement