public void AddEdge(Edge e)
 {
     int v = e.Either, w = e.Other(v);
     adj[v].Add(e);
     adj[w].Add(e);
     E++;
 }
Esempio n. 2
0
        private static bool FindAndUnion(List<HashSet<Node>> trees, Edge currentEdge)
        {
            Node[] nodes = new Node[] { currentEdge.Start, currentEdge.End };

            int firstTreeIndex = 0;
            int secondTreeIndex = 0;
            for (int i = 0; i < trees.Count; i++)
            {
                if (trees[i].IsSupersetOf(nodes))
                {
                    return false;
                }

                if (trees[i].Contains(currentEdge.Start))
                {
                    firstTreeIndex = i;
                    continue;
                }

                if (trees[i].Contains(currentEdge.End))
                {
                    secondTreeIndex = i;
                    continue;
                }
            }

            trees[firstTreeIndex].UnionWith(trees[secondTreeIndex]);
            trees.RemoveAt(secondTreeIndex);
            return true;
        }
Esempio n. 3
0
        private void FindPath(int startNode)
        {
            List<int> unprocessedNodesIdxs = new List<int>();
            foreach(var n in _Graph.Keys)
            {
                _ClosestNodes[n] = new Edge { Distance = decimal.MaxValue };
                unprocessedNodesIdxs.Add(n);
            }
            _ClosestNodes[startNode].Distance = 0;

            while(unprocessedNodesIdxs.Count > 0)
            {
                var currentNodeIdx = unprocessedNodesIdxs.First(p => _ClosestNodes[p].Distance == unprocessedNodesIdxs.Min(pp => _ClosestNodes[pp].Distance));
                unprocessedNodesIdxs.Remove(currentNodeIdx);

                foreach(var outEdge in _Graph[currentNodeIdx])
                {
                    decimal currentDistance = _ClosestNodes[outEdge.NextNodeId].Distance;
                    decimal newDistance = Math.Min(currentDistance, _ClosestNodes[currentNodeIdx].Distance + outEdge.EdgeVeight);
                    if(newDistance < currentDistance)
                    {
                        _ClosestNodes[outEdge.NextNodeId].Distance = newDistance;
                        _ClosestNodes[outEdge.NextNodeId].NextNodeId = currentNodeIdx;
                    }
                }
            }
        }
Esempio n. 4
0
        public void setUpByEdge(Edge TempEdge,bool isBothWay)
        {
            var result = TableOfMazes.Select(i =>
            {
                if (i.VertexNumber == TempEdge.Source()) i.Neigboors.Add(TempEdge.Dest());
                return i;
            }).ToList();
            if (isBothWay)
            {
                var resultTwo = TableOfMazes.Select(i =>
                    {
                        if (i.VertexNumber == TempEdge.Dest()) i.Neigboors.Add(TempEdge.Source());
                        return i;
                    }).ToList();
            }
             //   var temp = TableOfMazes.FirstOrDefault(c => c.VertexNumber == TempEdge.Source());
              //  if (temp != null)
              //  {
              //  Debug.WriteLine("kjhjkhjkhjk");
             //  // temp.Neigboors.Add(TempEdge.Dest());
             ////   }
             //   var temp = TableOfMazes.Find(r => (r.VertexNumber == TempEdge.Source()));
              //      temp.Neigboors.Add(TempEdge.Dest());
            //    TableOfMazes.ElementAt(r => (r.VertexNumber == TempEdge.Source())).Neigboors.Add(TempEdge.Dest());

               // TableOfMazes.ElementAtOrDefault(TempEdge.Source());
              //  TableOfMazes
        }
Esempio n. 5
0
        public TabStub(VisualStyle style)
        {
            // Default state
            _wct = null;
            _style = style;
            _hoverOver = -1;
            _hoverItem = -1;
            _selectedIndex = -1;
            _defaultFont = true;
            _defaultColor = true;
            _edge = Edge.None;
            _drawTabs = new ArrayList();
            _tabPages = new TabPageCollection();
            base.Font = SystemInformation.MenuFont;

            // Hookup to collection events
            _tabPages.Cleared += new CollectionClear(OnClearedPages);
            _tabPages.Inserted += new CollectionChange(OnInsertedPage);
            _tabPages.Removing += new CollectionChange(OnRemovingPage);
            _tabPages.Removed += new CollectionChange(OnRemovedPage);

            // Need notification when the MenuFont is changed
            Microsoft.Win32.SystemEvents.UserPreferenceChanged += new
                UserPreferenceChangedEventHandler(OnPreferenceChanged);

            // Default default colors
            DefineBackColor(SystemColors.Control);

            // Create the Timer for handling hovering over items
            _hoverTimer = new Timer();
            _hoverTimer.Interval = _hoverInterval;
            _hoverTimer.Tick += new EventHandler(OnTimerExpire);
        }
Esempio n. 6
0
 public void RemoveEdge(Edge aEdge)
 {
     if (aEdge != null && mEdges.Contains(aEdge))
         mEdges.Remove(aEdge);
     else
         throw new GraphException("hrana v grafu neexistuje", GraphExampleMessageType.EDGE);
 }
Esempio n. 7
0
 /// <summary>
 /// This method is used for making EdgeWrapper object that can be sent on clint, from Edge<Guid, EdgeData>.
 /// </summary>
 /// <param name="edge">data that need to be sent to client</param>
 /// <returns>EdgeWrapper object that is prepared for sending</returns>
 public static EdgeWrapper TransformeEdge(Edge<Guid, EdgeData> edge)
 {
     EdgeWrapper edgeDataWraper = new EdgeWrapper();
     edgeDataWraper.ToNodeId = edge.ToNodeId;
     edgeDataWraper.Data = EdgeDataWrapper.TransformeEdgeData(edge.Data);
     return edgeDataWraper;
 }
Esempio n. 8
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="edge"></param>
 /// <param name="graphNode"></param>
 public void AddGraphNode(Edge edge, int parentGraphNodeId, GraphNode graphNode)
 {
     GraphNode parent = GetGraphNodeById(parentGraphNodeId);
     edge.StartGraphNodeId = parentGraphNodeId;
     edge.EndGraphNodeId = graphNode.GraphNodeId;
     EdgeCollection.Add(edge);
 }
Esempio n. 9
0
		internal Margin(string otherControlName, Edge othersEdge, float distance)
			: this()
		{
			OtherControlName = otherControlName;
			OthersEdge = othersEdge;
			Distance = distance;
		}
Esempio n. 10
0
        //public NavigationTriangle(Vector3 a, Vector3 b, Vector3 c)
        public NavigationTriangle(Edge e1, Edge e2, Edge e3)
        {
            //m_neighbours[0] = null; // neighbour on a -> b side
            //m_neighbours[1] = null; // neighbour on b -> c side
            //m_neighbours[2] = null; // neighbour on c -> a side

            m_edge1 = e1;
            m_edge2 = e2;
            m_edge3 = e3;

            Vector3 a,b,c;
            m_edge1.getCommonVertex(m_edge3, out a);
            m_edge1.getCommonVertex(m_edge2, out b);
            m_edge2.getCommonVertex(m_edge3, out c);

            m_corners[0] = a;
            m_corners[1] = b;
            m_corners[2] = c;

            m_dirs[0] = Vector3.Subtract(c, a);
            m_dirs[1] = Vector3.Subtract(b, a);

            m_normal = Vector3.Cross(m_dirs[0], m_dirs[1]);
            m_normal.Normalize();
        }
Esempio n. 11
0
        internal static Edge Bisect(Site s1, Site s2)
        {
            var newEdge = new Edge();
            newEdge.Sites[LR.Left] = s1;
            newEdge.Sites[LR.Right] = s2;

            newEdge.Vertices[LR.Left] = newEdge.Vertices[LR.Right] = null;
            var dx = s2.Coord.X - s1.Coord.X;
            var dy = s2.Coord.Y - s1.Coord.Y;
            var adx = dx > 0 ? dx : -dx;
            var ady = dy > 0 ? dy : -dy;
            newEdge.C = s1.Coord.X*dx + s1.Coord.Y*dy + (dx*dx + dy*dy)*0.5f;
            if (adx > ady) {
                newEdge.A = 1.0f;
                newEdge.B = dy/dx;
                newEdge.C /= dx;
            } else {
                newEdge.B = 1.0f;
                newEdge.A = dy/dx;
                newEdge.C /= dy;
            }
            newEdge.EdgeID = NumEdges;
            Out.Bisector(newEdge);
            NumEdges++;
            return newEdge;
        }
        public void CheckPredecessorLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);

            var dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, e => 1);
            var vis = new VertexPredecessorRecorderObserver<int, Edge<int>>();
            using(vis.Attach(dij))
                dij.Compute(1);

            IEnumerable<Edge<int>> path;
            Assert.IsTrue(vis.TryGetPath(2, out path));
            var col = path.ToList();
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            Assert.IsTrue(vis.TryGetPath(3, out path));
            col = path.ToList();
            Assert.AreEqual(2, col.Count);
            Assert.AreEqual(e12, col[0]);
            Assert.AreEqual(e23, col[1]);
        }
Esempio n. 13
0
 static void Main(string[] args)
 {
     
     while (true)
     {
         s = Console.ReadLine();
         if (s == null)
             break;
         inp = s.Split(sep, StringSplitOptions.RemoveEmptyEntries);
         n = int.Parse(inp[0]);
         m = int.Parse(inp[1]);
         inp = Console.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries);
         o = int.Parse(inp[0]) - 1;
         d = int.Parse(inp[1]) - 1;
         for (int i = 0; i < m; i++)
         {
             inp = Console.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries);
             edges[i] = new Edge(int.Parse(inp[0]) - 1, int.Parse(inp[1]) - 1, double.Parse(inp[2]), double.Parse(inp[3]));
         }
         bellman_ford(o, n, m, -1);
         double temp = data[0, d];
         bellman_ford(o, n, m, temp);
         LinkedList<int> path = Path(o, d);
         LinkedListNode<int> aux = path.First;
         while (aux != path.Last)
         {
             Console.Write(aux.Value + 1 + " ");
             aux = aux.Next;
         }
         Console.WriteLine(aux.Value + 1);
         Console.WriteLine("{0} {1}", data[0, d].ToString(".0"), temp.ToString(".0"));
     }
 }
Esempio n. 14
0
        static int maxFlow(List<Edge>[] graph, int s, int t)
        {
            int flow = 0;
                    int[] q = new int[graph.Count()];
                    while (true) {
                      int qt = 0;
                      q[qt++] = s;
                      Edge[] pred = new Edge[graph.Count() ];
                      for (int qh = 0; qh < qt && pred[t] == null; qh++) {
                        int cur = q[qh];

                        foreach(Edge e in graph[cur]) {
                          if (pred[e.t] == null && e.cap > e.f) {
                            pred[e.t] = e;
                            q[qt++] = e.t;
                          }
                        }
                      }
                      if (pred[t] == null)
                        break;
                      int df = int.MaxValue;
                      for (int u = t; u != s; u = pred[u].s)
                        df = Math.Min(df, pred[u].cap - pred[u].f);
                      for (int u = t; u != s; u = pred[u].s) {
                        pred[u].f += df;
                        graph[pred[u].t].ElementAt(pred[u].rev).f -= df;
                      }
                      flow += df;
                    }
                    return flow;
        }
Esempio n. 15
0
		public static void expandSide( ref Rectangle rect, Edge edge, int amount )
		{
			// ensure we have a positive value
			amount = Math.Abs( amount );

			switch( edge )
			{
				case Edge.Top:
					rect.Y -= amount;
					rect.Height += amount;
					break;
				case Edge.Bottom:
					rect.Height += amount;
					break;
				case Edge.Left:
					rect.X -= amount;
					rect.Width += amount;
					break;
				case Edge.Right:
					rect.Width += amount;
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
		}
Esempio n. 16
0
 public void AddEdge(Node nodeFrom, Node nodeTo, float capacity)
 {
     var key = GetKey(nodeFrom.Id, nodeTo.Id);
     var edge = new Edge() { NodeFrom = nodeFrom, NodeTo = nodeTo, Capacity = capacity, Name = key };
     Edges.Add(key, edge);
     nodeFrom.NodeEdges.Add(edge);
 }
Esempio n. 17
0
        public void User_story_throws_out_of_bounds_exception_for_position_less_than_one()
        {
            var userStory = new UserStory(2);
            var edge = new Edge();

            Assert.That(() => edge.SetPosition(0, userStory), Throws.TypeOf<IndexOutOfRangeException>());
        }
Esempio n. 18
0
 public void AddEdge(Node nodeFrom, Node nodeTo, int capacity)
 {
     var key = GetKey(nodeFrom, nodeTo);
     var edge = new Edge { NodeFrom = nodeFrom, NodeTo = nodeTo, Capacity = capacity };
     edges.Add(key, edge);
     nodeFrom.NodeEdges.Add(edge);
 }
Esempio n. 19
0
        /// <summary>
        /// This method is used for getting Edge<Guid, EdgeData> from object that should be Edge.
        /// </summary>
        /// <param name="objectToParse">object that need to be transformed into Edge, 
        /// if this is not possible this method throw an Exception</param>
        /// <returns>Edge<Guid, EdgeData> that represent transformed object from objectToParse.
        /// If objectToParse is null, this method will return null</returns>
        public static Edge<Guid, EdgeData> ParseEdge(Object objectToParse)
        {
            if (objectToParse == null)
            {
                return null;
            }
            if (objectToParse is Dictionary<String, Object>)
            {
                Dictionary<String, Object> dictionaryToParse = objectToParse as Dictionary<String, Object>;
                if(dictionaryToParse.ContainsKey(TO_NODE_ID) && dictionaryToParse.ContainsKey(DATA))
                {
                    Guid toNodeId = (Guid)ObjectWrapper.ParseObjectWrapper(dictionaryToParse[TO_NODE_ID]);
                    EdgeData edgeData = (EdgeData)EdgeDataWrapper.ParseEdgeData(dictionaryToParse[DATA]);

                    Edge<Guid, EdgeData> edge = new Edge<Guid, EdgeData>(toNodeId, edgeData);

                    return edge;
                }
                else
                {
                    throw new Exception("Edge object is not formated in right way!");
                }
            }
            else
            {
                throw new Exception("Edge object is not formated in right way!");
            }
        }
Esempio n. 20
0
        public Node Clone()
        {
            Node cloneNode = new Node();
            cloneNode.ID = this.ID;
            cloneNode.PathName = this.PathName;
            cloneNode.PathID = this.PathID;
            cloneNode.IsExchangeSta = this.IsExchangeSta;
            cloneNode.dMapX = this.dMapX;
            cloneNode.dMapY = this.dMapY;
            cloneNode.StaName = this.StaName;
            cloneNode.GPS = this.GPS;

            ArrayList edges = new ArrayList();

            for (int i = 0; i < this.EdgeList.Count; i++)
            {
                Edge curE = this.EdgeList[i] as Edge;
                Edge e = new Edge();

                e.EdgeDirection = curE.EdgeDirection;
                e.EndNodeID = curE.EndNodeID;
                e.IsStep = curE.IsStep;
                e.SatrtNodeID = curE.SatrtNodeID;
                e.Weight = curE.Weight;

                edges.Add(e);
            }
            cloneNode.EdgeList = edges;

            return cloneNode;
        }
Esempio n. 21
0
        public static Vertex Rung4(GraphData d)
        {
            Vertex v = new Vertex();
            v.Include = Root + "Rung4.html";
            Edge e;

            string NextVertexName = "TraditionalCrises_Rung5";

            e = new Edge(d);
            e.State.VertexName = NextVertexName;
            //e.State.Stakes += 5;
            e.HTML = "A public and irrevocable increase in the stakes";
            v.Edges.Add(e);


            e = new Edge(d);
            e.State.VertexName = NextVertexName;
            //e.State.PublicAwareness += 20;
            e.HTML = "Officially inspire newspaper stories to the effect that the chief of state takes a serious view of the matter.";
            v.Edges.Add(e);

            


            return v;
        }
Esempio n. 22
0
        public void TestEdgeIntersection()
        {
            Edge edge;
            Point p1, p2, intersection;
            bool result;
            object[,] tests = { {4.0, 4.0, 6.0, 2.0, false, 0.0, 0.0},
                                {0.0, 2.0, 6.0, -1.0, true, 2.0, 1.0},
                                {0.0, 2.0, 6.0, 2.0, true, 4.0, 2.0},
                                {6.0, -1.0, 2.0, -3.0, false, 0.0, 0.0} };

            edge = new Edge(0, 0, 4, 2);
            for (int i = 0; i < tests.GetLength(0); i++)
            {
                p1 = new Point((double)tests[i, 0], (double)tests[i, 1]);
                p2 = new Point((double)tests[i, 2], (double)tests[i, 3]);

                result = edge.ComputeIntersection(new Edge(p1, p2), out intersection);

                Assert.Equals(result, tests[i, 4]);
                if (result)
                {
                    p1 = new Point((double)tests[i, 5], (double)tests[i, 6]);
                    Assert.Equals(p1.X, intersection.X);
                    Assert.Equals(p1.Y, intersection.Y);
                }
            }
        }
Esempio n. 23
0
        public void Simple()
        {
            var graph = new Graph<int>(false);

            var vertices = new Vertex<int>[20];

            for (var i = 0; i < 20; i++)
            {
                vertices[i] = new Vertex<int>(i);
                graph.AddVertex(vertices[i]);
            }

            for (var i = 0; i < 17; i += 2)
            {
                var edge = new Edge<int>(vertices[i], vertices[i + 2], false);
                graph.AddEdge(edge);
            }

            var trackingVisitor = new TrackingVisitor<int>();

            graph.AcceptVisitor(trackingVisitor);

            Assert.AreEqual(trackingVisitor.TrackingList.Count, 20);

            for (var i = 0; i < 20; i++)
            {
                Assert.IsTrue(trackingVisitor.TrackingList.Contains(i));
            }
        }
Esempio n. 24
0
 public void AddEdge(Edge e)
 {
     //Edge should have this node as one of the end nodes
     Contract.Requires((e.StartNode.Equals(this)) ||
                   (e.EndNode.Equals(this)));
     edges.Add(e);
 }
Esempio n. 25
0
        /// <summary>
        /// Erstellt ein neues Informationsobjekt für ein 3D-Modell, das eine Kante darstellt.
        /// [base="pipe1", Angles3.Zero, new Vector3 (10,10,10)]
        /// </summary>
        public Pipe(IScreen screen, IGrid grid, Knot knot, Edge edge, Node node1, Node node2)
            : base(screen: screen)
        {
            UniqueKey = edge.ToString ();

            // Weise Knoten und Kante zu
            Knot = knot;
            Edge = edge;
            Grid = grid;

            // Berechne die beiden Positionen, zwischen denen die Kante gezeichnet wird
            PositionFrom = node1;
            PositionTo = node2;

            // Kanten sind verschiebbar und auswählbar
            IsMovable = true;
            IsSelectable = true;

            // Berechne die Drehung
            Rotation += RotationMap [Edge.Direction];

            // Aktualisiere die Kategorie
            Coloring.OnColorChanged += UpdateCategory;
            IsSingleColored = true;

            incomplete = true;
        }
Esempio n. 26
0
        public static Vertex Intro(GraphData d)
        {
            Vertex v = new Vertex();
            v.Include = Root + "Intro.html";
            Edge e;



            e = new Edge(d);
            e.State.VertexName = "SubcrisisManeuvering_Index";
            e.State.Rank1.InHand += 1;
            e.State.Rank2_dipl.InHand += 2;
            e.State.Rank2_econ.InHand += 1;
            e.State.Rank2_poli.InHand += 1;

            e.HTML = "Assume political control over crisis. Communicate with allies' political leaders, confirm a firm leadership position in NATO and with non-NATO allies. Establish continuous high level lines of communication. Summon political advisors.";
            v.Edges.Add(e);

            e = new Edge(d);
            e.State.VertexName = "SubcrisisManeuvering_Index";
            e.Disabled = true;
            e.State.Rank3.InHand += 1;
            e.HTML = "Summon military leadership. Confirm command and control links over allies military leadership. Immediately address the nation.";
            v.Edges.Add(e);

            return v;
        }
Esempio n. 27
0
	    public bool ContainsEdge(Transaction tx, Edge edge)
        {
	        if (tx == null) throw new ArgumentNullException("tx");
	        if (edge == null) throw new ArgumentNullException("edge");

	        return tx.EdgeTree.ReadVersion(tx.VoronTransaction, edge.Key.ToSlice()) > 0;
        }
Esempio n. 28
0
			bool AddEdge(Edge e) {
				edges.Add(e);
				if(GetAdjacencyList(e.a).Contains(e.b)) return true; // linear, but list should be v. small
				GetAdjacencyList(e.a).AddLast(e.b); 
				GetAdjacencyList(e.b).AddLast(e.a); 
				return false;
			}
Esempio n. 29
0
        public IEnumerable<Intersection> FindIntersections(Edge e)
        {
            // points of edge reffered to as p and q
            Vector3 p = e.A;
            Vector3 q = e.B;
            Vector3 pq = q - p;
            double d = pq * N; // abs(d) is dist b/w p and q perp to triangle plane
            if (d == 0) return Enumerable.Empty<Intersection>(); // pq is paralell to the plane

            Vector3 pa = A - p;
            double t = pa * N; // perp dist from triangle plane to p
            if (t * d < 0) return Enumerable.Empty<Intersection>(); // q is further from the plane than p is
            if (Math.Abs(t) > Math.Abs(d)) return Enumerable.Empty<Intersection>(); // pq does not intersect the plane

            // at this point we know the edge intersects the plane that the triangle is in
            // but we don't know if it intersects the actual triangle

            Vector3 r = p + (t / d) * pq; // point of intersection with the plane

            Vector3 ra = A - r;
            double rab = ra * ABN; // dist b/w intersection and segment ab
            if (rab < 0) return Enumerable.Empty<Intersection>(); // outside of segment ab

            Vector3 rb = B - r;
            double rbc = rb * BCN;
            if (rbc < 0) return Enumerable.Empty<Intersection>(); // outside of segment bc

            Vector3 rc = C - r;
            double rac = rc * ACN;
            if (rac < 0) return Enumerable.Empty<Intersection>(); // outside of ac

            return new[] { new Intersection(r, N) };
        }
Esempio n. 30
0
 public EdgeModel(Edge e)
 {
     StartVillageId = e.FromVillageId;
     EndVillageId = e.ToVillageId;
     DistanceInSeconds = e.Time;
     DistanceMeasurementType = e.TimeType;
 }