Inheritance: Object
        public DvcsGraph()
        {
            syncContext = SynchronizationContext.Current;
            graphData = new Graph();

            backgroundThread = new Thread(BackgroundThreadEntry)
                                   {
                                       IsBackground = true,
                                       Priority = ThreadPriority.BelowNormal,
                                       Name = "DvcsGraph.backgroundThread"
                                   };
            backgroundThread.Start();

            InitializeComponent();

            ColumnHeadersDefaultCellStyle.Font = SystemFonts.DefaultFont;
            Font = SystemFonts.DefaultFont;
            DefaultCellStyle.Font = SystemFonts.DefaultFont;
            AlternatingRowsDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowsDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowHeadersDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowTemplate.DefaultCellStyle.Font = SystemFonts.DefaultFont;
            dataGridColumnGraph.DefaultCellStyle.Font = SystemFonts.DefaultFont;

            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            CellPainting += dataGrid_CellPainting;
            ColumnWidthChanged += dataGrid_ColumnWidthChanged;
            Scroll += dataGrid_Scroll;
            graphData.Updated += graphData_Updated;

            VirtualMode = true;
            Clear();
        }
示例#2
0
        public void Undirected()
        {
            var graph = new Graph<int>(false);
            var vertex1 = new Vertex<int>(1);
            var vertex2 = new Vertex<int>(2);
            var vertex3 = new Vertex<int>(3);

            graph.AddVertex(vertex1);
            graph.AddVertex(vertex2);
            graph.AddVertex(vertex3);

            graph.AddEdge(vertex1, vertex2);

            Assert.AreEqual(vertex1.IncomingEdgeCount, 0);
            Assert.AreEqual(vertex2.IncomingEdgeCount, 0);

            graph.AddEdge(vertex3, vertex2);

            Assert.AreEqual(vertex3.IncomingEdgeCount, 0);
            Assert.AreEqual(vertex2.IncomingEdgeCount, 0);

            graph.AddEdge(vertex1, vertex3);

            Assert.AreEqual(vertex1.IncomingEdgeCount, 0);
            Assert.AreEqual(vertex3.IncomingEdgeCount, 0);
        }
                /// <summary>
                /// Generate a path from a set of single-source parent pointers.
                /// </summary>
                /// <param name="from">The start of the path.</param>
                /// <param name="to">The end of the path.</param>
                /// <param name="parents">The set of single-source parent pointers.</param>
                /// <param name="graph">The graph to find the path in.</param>
                /// <returns>The path between <paramref name="from"/> and <paramref name="to"/>, if one exists; <code>null</code> otherwise.</returns>
                public static Path FromParents(uint from, uint to, Dictionary<uint, uint> parents, Graph graph)
                {
                    if (!parents.ContainsKey(to))
                        return null;

                    Path path = new Path();

                    path.Vertices.Add(graph.Vertices[to]);
                    uint current = to, parent;
                    while (parents.TryGetValue(current, out parent))
                    {
                        Vertex v = graph.Vertices[parent];
                        Edge e = v.Neighbours[current];
                        path.Edges.Add(e);
                        path.Vertices.Add(v);
                        path.Weight += e.Weight;
                        path.Capacity = Math.Min(path.Capacity, e.Capacity);
                        current = parent;
                    }

                    path.Edges.Reverse();
                    path.Vertices.Reverse();

                    return path;
                }
示例#4
0
        public void NodesDistinct()
        {
            Graph g = new Graph();
            List<INode> test = new List<INode>()
            {
                g.CreateUriNode("rdf:type"),
                g.CreateUriNode(new Uri("http://example.org")),
                g.CreateBlankNode(),
                g.CreateBlankNode(),
                null,
                g.CreateBlankNode("test"),
                g.CreateLiteralNode("Test text"),
                g.CreateLiteralNode("Test text", "en"),
                g.CreateLiteralNode("Test text", new Uri(XmlSpecsHelper.XmlSchemaDataTypeString)),
                g.CreateUriNode("rdf:type"),
                null,
                g.CreateUriNode(new Uri("http://example.org#test")),
                g.CreateUriNode(new Uri("http://example.org"))
            };

            foreach (INode n in test.Distinct())
            {
                if (n != null)
                {
                    Console.WriteLine(n.ToString());
                }
                else
                {
                    Console.WriteLine("null");
                }
            }
        }
    public void BuildLevel(Board board)
    {
        var children = new List<GameObject>();
        foreach (Transform child in transform)
            children.Add(child.gameObject);
        children.ForEach(child => Destroy(child));

        originalMatrix = board.Grid;
        matrix = PrepareMatrix(originalMatrix);
        int n = board.NoRooms;
        floors = new Floor[matrix.GetLength(0)-2,matrix.GetLength(1)-2];
        walls = new Wall[matrix.GetLength(0)-1, matrix.GetLength(1)-1];
        Rooms = new Room[n];
        graph = new Graph();
        for (int i = 0; i < n; ++i)
        {
            Rooms[i] = new Room(i+1, DefaultFloorMaterial);
        }
        RoomPropertiesPanel.InitializePanel(n);
        Vector3 shift = new Vector3(((matrix.GetLength(1) - 2) * unit) / 2, 0f, ((matrix.GetLength(0) - 2) * -unit) / 2);
        this.transform.position = shift;
        SpawnWalls();
        SpawnFloors();
        SpawnDoors();
        foreach (var room in Rooms)
        {
            room.SetRoomMaterial();
        }
        isSaved = false;
    }
示例#6
0
        public GraphVisualizerForm(Graph graph, string caption)
        {
            _graph = graph;
            _caption = caption;

            InitializeComponent();
        }
示例#7
0
        int widthForm, heightForm; // размеры основной формы

        #endregion Fields

        #region Constructors

        public FormSprite()
        {
            InitializeComponent();

            widthForm = this.Size.Width;
            heightForm = this.Size.Height;
            stepNet = 10;
            stepShift = 1;

            toolStripLabelXW.Text = "xW=" + this.Size.Width;
            toolStripLabelYW.Text = "yW=" + this.Size.Height;

            toolStripComboBoxWidthPen.SelectedIndex = 2;
            toolStripComboBoxStepNet.SelectedIndex = 0;
            toolStripComboBoxShift.SelectedIndex = 0;

            graph = new Graph(picture.Width, picture.Height);
            sprite = new Sprite();
            currPens = new DataSprite.Pens(ColorTranslator.ToHtml(Color.Black), 3);
            currFigure = new MyLine(currPens, 1, 1, 1, 1);

            flagLine = false;

            picture.Image = graph.GetBitmap;
        }
示例#8
0
        static void Main(string[] args)
        {
            Graph UG = new Graph(true);
            Vertex a = new Vertex("a");
            Vertex b = new Vertex("b");
            Vertex c = new Vertex("c");
            Vertex d = new Vertex("d");
            Vertex e = new Vertex("e");

            Vertex f = new Vertex("f");

            // Add vertexes
            UG.AddVertex(a);
            UG.AddVertex(b);
            UG.AddVertex(c);
            UG.AddVertex(d);
            UG.AddVertex(e);

            UG.AddEdge(a, b, 3);
            UG.AddEdge(a, c, 3);
            UG.AddEdge(b, d, 3);
            UG.AddEdge(d, e, 3);

            UG.BreadthFirstSearch(d);

            Console.ReadLine();
        }
示例#9
0
        public void StorageSesameSaveLoad()
        {
            try
            {
                Graph g = new Graph();
                FileLoader.Load(g, "InferenceTest.ttl");
                g.BaseUri = new Uri("http://example.org/SesameTest");

                SesameHttpProtocolConnector sesame = new SesameHttpProtocolConnector("http://nottm-virtual.ecs.soton.ac.uk:8080/openrdf-sesame/", "unit-test");
                sesame.SaveGraph(g);

                //Options.HttpDebugging = true;
                //Options.HttpFullDebugging = true;

                Graph h = new Graph();
                sesame.LoadGraph(h, "http://example.org/SesameTest");
                Assert.IsFalse(h.IsEmpty, "Graph should not be empty after loading");

                Assert.AreEqual(g, h, "Graphs should have been equal");
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Error", ex, true);
            }
            finally
            {
                //Options.HttpFullDebugging = false;
                //Options.HttpDebugging = true;
            }
        }
示例#10
0
        public void AddEdgeFromVerticesExample()
        {
            // Initialize a new graph instance
            var graph = new Graph<int>(true);

            // Add two vertices to the graph
            var vertex1 = graph.AddVertex(1);
            var vertex2 = graph.AddVertex(2);

            // Add the edge to the graph
            var edge = graph.AddEdge(vertex1, vertex2);

            // The from vertex will be vertex1
            Assert.AreEqual(edge.FromVertex, vertex1);

            // The to vertex will be vertex2
            Assert.AreEqual(edge.ToVertex, vertex2);

            // Since the graph is directed, the edge will
            // be directed as well
            Assert.AreEqual(edge.IsDirected, true);

            // The edge will be accessible though the edges collection
            Assert.AreEqual(graph.Edges.Count, 1);
        }
        public SymbolGraph(string[] graphData, char sp)
        {
            st = new BST<string, string>();

            for (int i = 0; i < graphData.Length; i++)
            {
                string[] a = graphData[i].Split(sp);
                foreach (string s in a)
                {
                    if (!st.Contains(s))
                    {
                        st.Put(s, st.Size().ToString());
                    }
                }
            }

            keys = new string[st.Size()];

            foreach (string key in st.Keys())
            {
                keys[int.Parse(st.Get(key))] = key;
            }

            graph = new Graph(st.Size());

            foreach (string data in graphData)
            {
                string[] a = data.Split(sp);
                int v = int.Parse(st.Get(a[0]));
                for (int i = 1; i < a.Length; i++)
                {
                    graph.AddEdge(v, int.Parse(st.Get(a[i])));
                }
            }
        }
示例#12
0
 public string Solve()
 {
     var d = new Dijkstra(graph);
     graph = d.Calculate();
     SelectResult(graph);
     return result.Max(g => g.PathLength).ToString(CultureInfo.InvariantCulture);
 }
示例#13
0
        private void LoadData()
        {
            var rows = File.ReadAllLines(DataFile);
            graphDepth = rows.Length;
            graph = new Graph(0) {PathLength = int.Parse(rows[0])};
            var lastGraphs = new Graph[1];
            lastGraphs[0] = graph;
            for (var i = 1; i < rows.Length; i++)
            {
                var values = rows[i].Split(' ').Select(int.Parse).ToArray();
                var graphs = new Graph[values.Length];
                for (var j = 0; j < values.Length; j++)
                {
                    graphs[j] = new Graph(i);
                    if (j != values.Length - 1)
                    {
                        lastGraphs[j].connectionList.Add(graphs[j], values[j]);
                    }

                    if (j != 0)
                    {
                        lastGraphs[j-1].connectionList.Add(graphs[j], values[j]);
                    }
                }
                lastGraphs = graphs;

            }
        }
示例#14
0
        /// <summary>
        /// Creates a new VoID Description which is loaded from the given File
        /// </summary>
        /// <param name="file">Filename</param>
        public VoIDDescription(String file)
        {
            Graph g = new Graph();
            FileLoader.Load(g, file);

            this.Initialise(g);
        }
示例#15
0
        /// <summary>
        /// Creates a new VoID Description which is loaded from the given URI
        /// </summary>
        /// <param name="u">URI</param>
        public VoIDDescription(Uri u)
        {
            Graph g = new Graph();
            UriLoader.Load(g, u);

            this.Initialise(g);
        }
示例#16
0
        public DvcsGraph()
        {
            _graphData = new Graph();

            _backgroundThread = new Thread(BackgroundThreadEntry)
                                   {
                                       IsBackground = true,
                                       Priority = ThreadPriority.Normal,
                                       Name = "DvcsGraph.backgroundThread"
                                   };
            _backgroundThread.Start();

            InitializeComponent();

            ColumnHeadersDefaultCellStyle.Font = SystemFonts.DefaultFont;
            Font = SystemFonts.DefaultFont;
            DefaultCellStyle.Font = SystemFonts.DefaultFont;
            AlternatingRowsDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowsDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowHeadersDefaultCellStyle.Font = SystemFonts.DefaultFont;
            RowTemplate.DefaultCellStyle.Font = SystemFonts.DefaultFont;

            _whiteBorderPen = new Pen(Brushes.White, _laneLineWidth + 2);
            _blackBorderPen = new Pen(Brushes.Black, _laneLineWidth + 1);

            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            CellPainting += dataGrid_CellPainting;
            ColumnWidthChanged += dataGrid_ColumnWidthChanged;
            Scroll += dataGrid_Scroll;
            _graphData.Updated += graphData_Updated;

            VirtualMode = true;
            Clear();
        }
示例#17
0
        // Constructor for creating a new representative table. We directly fill the table depending on the given sequence.
        public RepresentativeTable(Graph graph, Tree tree)
        {
            // Initialize the table
            _table = new Dictionary<BitSet, RepresentativeList>();

            Queue<BitSet> queue = new Queue<BitSet>();
            queue.Enqueue(tree.Root);
            _table[new BitSet(0, graph.Size)] = new RepresentativeList();

            int i = 0;

            while (queue.Count != 0)
            {
                BitSet node = queue.Dequeue();

                FillTable(graph, node);
                FillTable(graph, graph.Vertices - node);

                if (tree.LeftChild.ContainsKey(node))
                {
                    queue.Enqueue(tree.LeftChild[node]);
                }
                if (tree.RightChild.ContainsKey(node))
                {
                    queue.Enqueue(tree.RightChild[node]);
                }
            }
        }
示例#18
0
        public Control()
        {
            InitializeComponent();

            selectionContainer = new Microsoft.VisualStudio.Shell.SelectionContainer();

            nextGraph = null;
            hasNextGraph = false;
            VSGraphVizPackage.expressionGraph.graphUpdated += graphUpdatedHandler;

            bc = new BrushConverter();

            showCompleted = true;
            animationCounter = 0;
            animationLock = new object();

            cur_alg = 1;

            grap_layout_algo = new List<GraphLayout>();
            grap_layout_algo.Add(new FRLayout());
            grap_layout_algo.Add(new RadialLayout());
            grap_layout_algo.Add(new RightHeavyHVLayout());

            graph_layout_algo_name = new List<string>();
            graph_layout_algo_name.Add("Fruchterman-Reingold");
            graph_layout_algo_name.Add("Radial");
            graph_layout_algo_name.Add("Right-Heavy HV");

            gen_menu();
        }
示例#19
0
        public Graph CreateTubeGraph()
        {
            var graph = new Graph();

            // add all the nodes here
            foreach (var station in new Constants().GetStations())
            {
                graph.AddNode(station);
            }

            // add the connections

            graph.AddConnection(Constants.Embankment, Constants.Temple, 2, ConnectionMedium.DistrictAndCircle);
            graph.AddConnection(Constants.Embankment, Constants.CharingCross, 5, ConnectionMedium.Walking);
            graph.AddConnection(Constants.Embankment, Constants.CharingCross, 2, ConnectionMedium.Bakerloo);
            graph.AddConnection(Constants.Embankment, Constants.CharingCross, 2, ConnectionMedium.Northern);
            graph.AddConnection(Constants.Temple, Constants.Blackfriars, 2, ConnectionMedium.DistrictAndCircle);
            graph.AddConnection(Constants.Blackfriars, Constants.MansionHouse, 2, ConnectionMedium.DistrictAndCircle);
            graph.AddConnection(Constants.MansionHouse, Constants.CannonStreet, 2, ConnectionMedium.DistrictAndCircle);
            graph.AddConnection(Constants.CannonStreet, Constants.Monument, 2, ConnectionMedium.DistrictAndCircle);
            graph.AddConnection(Constants.Monument, Constants.Bank, 5, ConnectionMedium.Walking);
            graph.AddConnection(Constants.Bank, Constants.StPauls, 2, ConnectionMedium.Central);
            graph.AddConnection(Constants.StPauls, Constants.ChanceryLane, 2, ConnectionMedium.Central);
            graph.AddConnection(Constants.ChanceryLane, Constants.Holborn, 2, ConnectionMedium.Central);
            graph.AddConnection(Constants.Holborn, Constants.CoventGarden, 2, ConnectionMedium.Piccadilly);
            graph.AddConnection(Constants.CoventGarden, Constants.LeicesterSquare, 2, ConnectionMedium.Piccadilly);
            graph.AddConnection(Constants.LeicesterSquare, Constants.TottenhamCourtRoad, 2, ConnectionMedium.Northern);
            graph.AddConnection(Constants.LeicesterSquare, Constants.CharingCross, 2, ConnectionMedium.Northern);

            return graph;
        }
示例#20
0
        public StatisticGraph(Control parent, SpriteFont font, Statistic statistic, TimeSpan accessInterval)
            : base(parent)
        {
            if (statistic == null)
                throw new ArgumentNullException("statistic");

            if (accessInterval == TimeSpan.Zero)
                accessInterval = TimeSpan.FromMilliseconds(16);

            Strata = new ControlStrata() { Layer = Layer.Overlay };
            _tracker = new StatisticTracker(statistic, accessInterval);
            _graph = new Graph(Device, (int)(15f / (float)accessInterval.TotalSeconds)); //(byte)MathHelper.Clamp(15f / (float)accessInterval.TotalSeconds, 15, 15 * 60));
            _label = new Label(this, font) {
                Text = statistic.Name,
                Justification = Justification.Centre
            };
            _label.SetPoint(Points.TopLeft, 2, 2);
            _label.SetPoint(Points.TopRight, -2, 2);

            _value = new Label(this, font) {
                Text = "0",
                Justification = Justification.Centre
            };
            _value.SetPoint(Points.BottomLeft, 2, -2);
            _value.SetPoint(Points.BottomRight, -2, -2);

            _texture = new Texture2D(Device, 1, 1);
            _texture.SetData<Color>(new Color[] { new Color(0, 0, 0, 0.8f) });

            SetSize(200, 120);
        }
示例#21
0
 public void aaaFakeLicenseDatabase()
 {
   Assert.Throws<NoValidVelocityDBLicenseFoundException>(() =>
   {
     using (SessionNoServer session = new SessionNoServer(systemDir))
     {
       session.BeginUpdate();
       Database database;
       License license = new License("Mats", 1, null, null, null, 99999, DateTime.MaxValue, 9999, 99, 9999);
       Placement placer = new Placement(License.PlaceInDatabase, 1, 1, 1);
       license.Persist(placer, session);
       for (uint i = 10; i < 20; i++)
       {
         database = session.NewDatabase(i);
         Assert.NotNull(database);
       }
       session.Commit();
       File.Copy(Path.Combine(systemDir, "20.odb"), Path.Combine(systemDir, "4.odb"));
       session.BeginUpdate();
       for (uint i = 21; i < 30; i++)
       {
         database = session.NewDatabase(i);
         Assert.NotNull(database);
       }
       session.RegisterClass(typeof(VelocityDbSchema.Samples.Sample1.Person));
       Graph g = new Graph(session);
       session.Persist(g);
       session.Commit();
     }
   });
 }
示例#22
0
        public void ShouldReplaceLinkInAll()
        {
            // arrange
            var source = new SampleNode("source");
            var target = new SampleNode("target");

            var graph = new Graph();
            graph.AddNode(source);
            graph.AddNode(target);

            var firstLink = new SampleLink();

            graph.AddLink(source, target, firstLink);

            var secondLink = new SecondLink();

            // act
            graph.ReplaceLink(firstLink, secondLink);

            // Assert
            Assert.That(graph.Links, Has.Count.EqualTo(1));
            Assert.That(graph.Links, Has.No.Member(firstLink));
            Assert.That(graph.Links, Has.Member(secondLink));

            Assert.That(secondLink.Source, Is.SameAs(source));
            Assert.That(secondLink.Target, Is.SameAs(target));

            Assert.That(source.OutboundLinks, Has.No.Member(firstLink));
            Assert.That(target.InboundLinks, Has.No.Member(firstLink));

            Assert.That(source.OutboundLinks, Has.Member(secondLink));
            Assert.That(target.InboundLinks, Has.Member(secondLink));
        }
        private void CheckCompressionRoundTrip(IGraph g)
        {
            foreach (KeyValuePair<IRdfWriter, IRdfReader> kvp in this._compressers)
            {

                IRdfWriter writer = kvp.Key;
                if (writer is ICompressingWriter)
                {
                    ((ICompressingWriter)writer).CompressionLevel = WriterCompressionLevel.High;
                }
                if (writer is IHighSpeedWriter)
                {
                    ((IHighSpeedWriter)writer).HighSpeedModePermitted = false;
                }
                System.IO.StringWriter strWriter = new System.IO.StringWriter();
                writer.Save(g, strWriter);

                Console.WriteLine("Compressed Output using " + kvp.Key.GetType().Name);
                Console.WriteLine(strWriter.ToString());
                Console.WriteLine();

                Graph h = new Graph();
                StringParser.Parse(h, strWriter.ToString(), kvp.Value);

                Assert.AreEqual(g, h, "Graphs should be equal after round trip to and from serialization using " + kvp.Key.GetType().Name);
            }
        }
    public static void Main()
    {
        var graph = new Graph(new[]
            {
                new List<int> {3, 6}, // children of node 0 (Ruse)
                new List<int> {2, 3, 4, 5, 6}, // children of node 1 (Sofia)
                new List<int> {1, 4, 5}, // children of node 2 (Pleven)
                new List<int> {0, 1, 5}, // children of node 3 (Varna)
                new List<int> {1, 2, 6}, // children of node 4 (Bourgas)
                new List<int> {1, 2, 3}, // children of node 5 (Stara Zagora)
                new List<int> {0, 1, 4}  // children of node 6 (Plovdiv)
            },
            new string[] { "Ruse", "Sofia", "Pleven", "Varna", "Bourgas", "Stara Zagora", "Plovdiv" }
        );

        // Print the nodes and their children
        for (int nodeIndex = 0; nodeIndex < graph.ChildNodes.Length; nodeIndex++)
        {
            Console.WriteLine("{0} -> {1}", nodeIndex,
                string.Join(" ", graph.ChildNodes[nodeIndex]));
        }

        Console.WriteLine();

        // Print the node names and their children names
        for (int nodeIndex = 0; nodeIndex < graph.ChildNodes.Length; nodeIndex++)
        {
            Console.WriteLine("{0} -> {1}",
                graph.NodeNames[nodeIndex],
                string.Join(", ", graph.ChildNodes[nodeIndex]
                    .Select(node => graph.NodeNames[node])));
        }
    }
示例#25
0
文件: Accept.cs 项目: havok/ngenerics
        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));
            }
        }
示例#26
0
        public PotentialMethod(Graph<int> orientedGraph, List<int> production)
        {
            S = orientedGraph;

            Production = production;
            IsFirstPhaseNeeded = true;
        }
示例#27
0
文件: AsyncTask.cs 项目: mparsin/TBMS
        internal override IList<Node> GenerateDiagram(Graph graph, Node parentNode)
        {
            var result = base.GenerateDiagram(graph, parentNode);

            var node = result[0];
            node.EscalationLevel = EscalationLevel;

            if (Escalations != null )
            {
                foreach (var escalation in Escalations)
                {
                    var nodes = escalation.GenerateDiagram(graph, node);
                    foreach (var childNode in nodes)
                    {
                        var link = graph.Links.FirstOrDefault(l => l.From == node && l.To == childNode);
                        if (link != null)
                        {
                            link.Text = $"Escalation Level {Escalations.IndexOf(escalation) + 1}";
                            link.Category = "Escalation";
                        }
                    }
                }
            }

            return result;
        }
示例#28
0
        public void hasAdjacentNodeTest()
        {
            try
            {

                Graph g = new Graph();
                Node n1 = new PointOfInterest(1, 0, 0, 1);
                Node n2 = new PointOfInterest(2, 0, 0, 1);
                Node n3 = new PointOfInterest(3, 0, 0, 1);

                g.InsertNewVertex(n1);
                g.InsertNewVertex(n2);
                g.InsertNewVertex(n3);

                n1.addListOfAdjacentNodes(new Dictionary<Node, float>() { { n2, 4 } });
                n2.addListOfAdjacentNodes(new Dictionary<Node, float>() { { n1, 3 } });
                Assert.IsNotNull(g);
                Assert.IsNotNull(n1);
                Assert.IsNotNull(n2);
                Assert.IsNotNull(n3);
                Assert.True(n1.isAdjacent(n2),
                    "This tests if isAdjacent returns true if a node is adjacent to a given one.");
            }
            catch (SecurityException e)
            {
                Console.WriteLine("Security Exception:\n\n{0}", e.Message);
            }
        }
        public void SparqlFunctionsIsNumeric()
        {
            Graph g = new Graph();
            IUriNode subj = g.CreateUriNode(new Uri("http://example.org/subject"));
            IUriNode pred = g.CreateUriNode(new Uri("http://example.org/predicate"));

            g.Assert(subj, pred, (12).ToLiteral(g));
            g.Assert(subj, pred, g.CreateLiteralNode("12"));
            g.Assert(subj, pred, g.CreateLiteralNode("12", new Uri(XmlSpecsHelper.XmlSchemaDataTypeNonNegativeInteger)));
            g.Assert(subj, pred, g.CreateLiteralNode("12", new Uri(XmlSpecsHelper.XmlSchemaDataTypeNonPositiveInteger)));
            g.Assert(subj, pred, g.CreateLiteralNode("1200", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)));
            g.Assert(subj, pred, ((byte)50).ToLiteral(g));
            g.Assert(subj, pred, g.CreateLiteralNode("-50", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)));
            g.Assert(subj, pred, g.CreateLiteralNode("-50", new Uri(XmlSpecsHelper.XmlSchemaDataTypeUnsignedByte)));
            g.Assert(subj, pred, g.CreateUriNode(new Uri("http://example.org")));

            TripleStore store = new TripleStore();
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString("SELECT ?obj (IsNumeric(?obj) AS ?IsNumeric) WHERE { ?s ?p ?obj }");

            Object results = store.ExecuteQuery(q);

            Assert.IsTrue(results is SparqlResultSet, "Result should be a SPARQL Result Set");
            TestTools.ShowResults(results);
        }
示例#30
0
 GraphGUIEx GetEditor(Graph graph)
 {
     GraphGUIEx graphGUI = ScriptableObject.CreateInstance<GraphGUIEx>();
     graphGUI.graph = graph;
     graphGUI.hideFlags = HideFlags.HideAndDontSave;
     return graphGUI;
 }
示例#31
0
 public MetricFFTBandEnergy(XmlNode node, Graph graph) : this(graph) { }
        private void TestOverlapRemovalOnGraph(string graphName, Graph parentGraph,
                                               HashSet <Tuple <int, int> > proximityEdges, HashSet <Tuple <int, int, int> > proximityTriangles,
                                               Tuple <String, Action <GeometryGraph> > layoutMethod, int layoutPos,
                                               Tuple <string, OverlapRemovalSettings> overlapMethod, int overlapMethodPos)
        {
//            Graph parentGraph = Helper.CopyGraph(parentGraphOriginal);
            var geomGraphOld = Helper.CopyGraph(parentGraph.GeometryGraph);
            var geomGraph    = parentGraph.GeometryGraph;

            graphName = Path.GetFileNameWithoutExtension(graphName);
//            GeometryGraph graph = Helper.CopyGraph(geomGraph);
            List <Tuple <String, double> > statistics = new List <Tuple <string, double> >();

            String layoutMethodName  = layoutMethod.Item1;
            String overlapMethodName = overlapMethod.Item1;
            var    overlapSettings   = overlapMethod.Item2;

            IOverlapRemoval overlapRemover = GetOverlapRemover(overlapSettings, geomGraph);

            overlapRemover.RemoveOverlaps();

            RouteGraphEdges(parentGraph);

            MakeEdgesTransparent(parentGraph);

            List <Tuple <string, double> > kClosestNeighborsError = new List <Tuple <string, double> >();
            var statIterations = RunStats(proximityEdges, proximityTriangles, overlapRemover, geomGraphOld, geomGraph,
                                          kClosestNeighborsError);

            foreach (var t in kClosestNeighborsError)
            {
                statistics.Add(t);
            }
            statistics.Add(statIterations);

            String nameAddon = "-" + layoutPos + "_" + overlapMethodPos + "-" + layoutMethodName + "_" +
                               overlapMethodName;

            parentGraph.GeometryGraph.UpdateBoundingBox();
            DumpProximityCdtToSvg("cdt_" + graphName + nameAddon + ".svg", parentGraph, proximityEdges);


            SvgGraphWriter.WriteAllExceptEdgesInBlack(parentGraph, graphName + nameAddon + ".svg");

            WriteHeader(statistics);
            String line = graphName + "," + geomGraph.Nodes.Count + "," + geomGraph.Edges.Count + "," + layoutMethodName +
                          "," + overlapMethodName;

            double closestNeighErr = 0;

            for (int i = 0; i < statistics.Count; i++)
            {
                Tuple <string, double> stat = statistics[i];
                line += "," + stat.Item2;
                if (stat.Item1.StartsWith("f"))
                {
                    closestNeighErr += stat.Item2;
                }
            }
            ErrorCouple ec;

            if (!_errorDict.TryGetValue(graphName, out ec))
            {
                ec = new ErrorCouple();
                _errorDict[graphName] = ec;
            }
            if (overlapMethodName.Contains("PRISM"))
            {
                ec.prismError = closestNeighErr;
            }
            else
            {
                ec.gtreeError = closestNeighErr;
            }

            WriteLine(line);
        }
//        private static List<double> _sharedFamilyForPrism=new List<double>();
//        static List<double> _sharedFamilyForGtree=new List<double>();
        /// <summary>
        ///
        /// </summary>
        /// <param name="graphFilename"></param>
        /// <param name="runLayout"></param>
        public void RunOverlapRemoval(string graphFilename, bool runLayout)
        {
            String graphName = Path.GetFileNameWithoutExtension(graphFilename);
            Graph  graph     = LoadGraphFile(graphFilename, runLayout);

            if (graph == null)
            {
                Console.WriteLine("Failed to load drawing graph: {0}", graphName);
                return;
            }
            if (graph.GeometryGraph == null)
            {
                Console.WriteLine("Failed to load geometry graph: {0}", graphName);
                return;
            }
            Point[] initPositions = graph.GeometryGraph.Nodes.Select(v => v.Center).ToArray();

            for (int i = 0; i < layoutMethods.Count(); i++)
            {
                var layoutMethod = layoutMethods[i];

                layoutMethod.Item2.Invoke(graph.GeometryGraph); //do initial layout
                //randomize cooincident points
                Point[] nodePositions = graph.GeometryGraph.Nodes.Select(v => v.Center).ToArray();

                //                LayoutAlgorithmSettings.ShowDebugCurves(
                //                    nodePositions.Select(p => new DebugCurve(220, 0.01, "green", CurveFactory.CreateOctagon(2, 2, p)))
                //                                 .ToArray());

                RandomizeNodes(graph, nodePositions);
                SvgGraphWriter.WriteAllExceptEdges(graph,
                                                   Path.GetFileNameWithoutExtension(graphName) + "-" + i.ToString() + "-" + layoutMethod.Item1 + ".svg");

                HashSet <Tuple <int, int, int> > proximityTriangles;
                HashSet <Tuple <int, int> >      proximityEdges;
                GetProximityRelations(graph.GeometryGraph, out proximityEdges, out proximityTriangles);
                DumpProximityCdtToSvg("cdt_" + graphName + "-" + i.ToString() + "-" + layoutMethod.Item1 + ".svg", graph, proximityEdges);
                for (int j = 0; j < overlapMethods.Count; j++)
                {
                    if (graph.NodeCount == 0)
                    {
                        continue;
                    }
                    var overlapMethod = overlapMethods[j];
                    TestOverlapRemovalOnGraph(graphName, graph, proximityEdges, proximityTriangles, layoutMethod, i,
                                              overlapMethod, j);
                    SetOldPositions(nodePositions, graph);
                }
                SetOldPositions(initPositions, graph);
            }



            //#if DEBUG
            //            //write the number of crossings per iteration
            //            String convergenceFilename = graphName + "-crossPerIterat.csv";
            //            List<int> crossings1 = prism1.crossingsOverTime;
            //            List<int> crossings2 = prism2.crossingsOverTime;
            //
            //            int maxIter = Math.Max(crossings1.Count, crossings2.Count);
            //            List<String> lines=new List<string>();
            //            lines.Add("iteration,crossingsPRISM,crossingsGridBoost");
            //            for (int i = 0; i < maxIter; i++) {
            //                String l = i.ToString();
            //                if (i < crossings1.Count)
            //                    l += "," + crossings1[i];
            //                else l += ",0";
            //                if (i < crossings2.Count)
            //                    l += "," + crossings2[i];
            //                else l += ",0";
            //                lines.Add(l);
            //            }
            //            File.WriteAllLines(convergenceFilename,
            //                lines.ToArray(),Encoding.UTF8);
            //#endif
        }
 private Point GetIthPoint(int i, Graph graph)
 {
     return(graph.GeometryGraph.Nodes[i].Center);
 }
示例#35
0
 public TextReportCreator(Graph graph, ISearchAlgorithm searchAlgorithm, IVertexColoringAlgorithm vertexColoringAlgorithm)
 {
     _graph                   = graph;
     _searchAlgorithm         = searchAlgorithm;
     _vertexColoringAlgorithm = vertexColoringAlgorithm;
 }
示例#36
0
        public void ExceptionNullVisitor()
        {
            var graph = new Graph <int>(false);

            graph.AcceptVisitor(null);
        }
示例#37
0
 // Use this for initialization
 void Start()
 {
     aGraph = new Graph();
     StartCoroutine(aGraph.DijkstraFun(1, 5));
 }
示例#38
0
 /// <summary>
 /// The solution of the geometric inference is injected
 /// directly into the variables and indices of the graph.
 /// </summary>
 public void Solve(Graph graph)
 {
     throw new NotImplementedException();
 }
        void CreateSubGraphFromSelected()
        {
            //Debug.Log("root graph " + rootGraph.name);
            Graph _subGraph = Graph.CreateSubGraph("SubGraph", rootGraph.currentGraph, rootGraph);

            _subGraph.isRoot    = false;
            _subGraph.rootGraph = rootGraph;

            rootGraph.currentGraph.subGraphs.Add(_subGraph);

            Vector2 _position = Vector2.zero;

            // Add selected nodes to subgraph
            foreach (var key in rootGraph.selectedNodes.Keys)
            {
                _subGraph.nodes.Add(rootGraph.selectedNodes[key]);
                rootGraph.selectedNodes[key].graphOwner = _subGraph;

                rootGraph.currentGraph.nodes.Remove(rootGraph.selectedNodes[key]);

                // disconnect input and output nodes which do not belong to subgraph
                for (int i = 0; i < rootGraph.selectedNodes[key].inputNodes.Count; i++)
                {
                    var  _isInSelection      = false;
                    Node _nodeNotInSelection = rootGraph.selectedNodes[key].inputNodes[i].inputNode;
                    foreach (var inputKey in rootGraph.selectedNodes.Keys)
                    {
                        if (rootGraph.selectedNodes[key].inputNodes[i].inputNode == rootGraph.selectedNodes[inputKey])
                        {
                            _isInSelection = true;
                        }
                    }

                    if (!_isInSelection)
                    {
                        rootGraph.selectedNodes[key].RemoveInputNode(_nodeNotInSelection);

                        for (int m = 0; m < _nodeNotInSelection.outputNodes.Count; m++)
                        {
                            if (_nodeNotInSelection.outputNodes[m].outputNode == rootGraph.selectedNodes[key])
                            {
                                _nodeNotInSelection.outputNodes[m].outputNode = null;
                            }
                        }
                    }
                }

                for (int o = 0; o < rootGraph.selectedNodes[key].outputNodes.Count; o++)
                {
                    var  _isInSelection      = false;
                    Node _nodeNotInSelection = rootGraph.selectedNodes[key].outputNodes[o].outputNode;
                    foreach (var outputKey in rootGraph.selectedNodes.Keys)
                    {
                        if (rootGraph.selectedNodes[key].outputNodes[o].outputNode == rootGraph.selectedNodes[outputKey])
                        {
                            _isInSelection = true;
                        }
                    }

                    if (!_isInSelection)
                    {
                        if (_nodeNotInSelection != null)
                        {
                            _nodeNotInSelection.RemoveInputNode(rootGraph.selectedNodes[key]);
                        }

                        rootGraph.selectedNodes[key].outputNodes[o].outputNode = null;
                    }
                }



                _position += rootGraph.selectedNodes[key].nodeRect.center;


                // clean up subgraph list
                // if we're nesting a selected subgraph we need to remove it from the current subgraph list and add it to the newly created subgraph
                if (rootGraph.selectedNodes[key].nodeData.nodeType == NodeAttributes.NodeType.SubGraph)
                {
                    var _subgraphNode = rootGraph.selectedNodes[key] as SubGraph;
                    rootGraph.currentGraph.subGraphs.Remove(_subgraphNode.subGraph);

                    _subGraph.subGraphs.Add(_subgraphNode.subGraph);
                }
            }



            _position /= rootGraph.selectedNodes.Keys.Count;

            var _subGraphNode = NodeCreator.CreateNode(null, rootGraph, rootGraph.currentGraph, "SubGraph", _position);

            var _sub = _subGraphNode as SubGraph;

            _sub.subGraph          = _subGraph;
            _subGraph.subGraphNode = _sub;

            Vector2 _enterGraphNodePosition = new Vector2(_position.x - 400, _position.y);
            Vector2 _exitGraphNodePosition  = new Vector2(_position.x - 400, _position.y + 80);

            // Create OnEnterGraph and OnExitGraph node
            NodeCreator.CreateNode(null, rootGraph, _subGraph, "OnEnterGraph", _enterGraphNodePosition);
            NodeCreator.CreateNode(null, rootGraph, _subGraph, "ExitGraph", _exitGraphNodePosition);



            // assign new rootgraph to all sub nodes
            for (int s = 0; s < rootGraph.subGraphs.Count; s++)
            {
                rootGraph.subGraphs[s].AssignNewRootGraph(rootGraph);
            }
        }
 public static bool HasCycle <T>(this Graph <T> graph)
 {
     return(GraphTarjanAlgorithm.TarjanAlgorithm(graph) == null);
 }
示例#41
0
 public static bool NonNullElements <T>(Graph <T> collection) where T : class
 {
     return(collection != null && NonNullElements(collection.TopologicallySortedComponents()));
 }
        private static void GenerateGraph(Options options)
        {
            var dependencyGraph = DependencyGraphSpec.Load(options.DependencyGrapthPath);
            var graph           = new Graph <string>();
            var projectVersions = new Dictionary <string, string>();

            foreach (var project in dependencyGraph.Projects.Where(p => p.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference))
            {
                //filtering test
                if (project.Name.Contains("test", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                graph.AddVertex(project.Name);
                projectVersions.Add(project.Name, project.Version.ToNormalizedString());
            }

            foreach (var project in dependencyGraph.Projects.Where(p => p.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference))
            {
                //filtering test
                if (project.Name.Contains("test", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                Console.WriteLine(project.Name);
                HashSet <string> dep = new HashSet <string>();
                foreach (var targetFramework in project.TargetFrameworks)
                {
                    foreach (var dependency in targetFramework.Dependencies)
                    {
                        //remove duplication
                        if (dep.Contains(dependency.Name))
                        {
                            continue;
                        }
                        dep.Add(dependency.Name);
                        if (graph.Vertices.Any(v => v == dependency.Name))
                        {
                            var notLastVersion = projectVersions[dependency.Name] != dependency.LibraryRange.VersionRange.ToShortString();
                            var attributes     = new Dictionary <string, string>()
                            {
                                { "label", dependency.LibraryRange.VersionRange.ToShortString() }
                            };
                            if (notLastVersion)
                            {
                                attributes.Add("color", "red");
                            }
                            else
                            {
                                attributes.Add("color", "green");
                            }
                            graph.AddEdge(new Edge <string>(project.Name, dependency.Name, attributes: attributes));
                        }
                    }
                }
            }

            var writer = new StringWriter();

            new GraphToDotConverter().Convert(writer, graph, new AttributesProvider(projectVersions));
            var graphContent = writer.GetStringBuilder().ToString().Trim();
            var dotFile      = Path.ChangeExtension(options.OutputFilePath, "dot");

            File.WriteAllText(dotFile, graphContent);
            var dotExec   = Path.Combine(options.GraphvizBinPath, "dot.exe");
            var arguments = $"-Tjpg {dotFile} -o {options.OutputFilePath}";

            ProcessAsyncHelper.ExecuteShellCommand(dotExec, arguments, int.MaxValue).Wait();
        }
示例#43
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="graph">The graph where the search will be performed</param>
 public DijkstraSearch(Graph <T, K> graph) : base(graph)
 {
 }
示例#44
0
        private void DrawConnectors(Rect p_rect)
        {
            GUISkin skin = DashEditorCore.Skin;

            // Inputs
            int count = InputCount;
            for (int i = 0; i < count; i++)
            {
                bool isConnected = Graph.HasInputConnected(this, i);
                GUI.color = isConnected
                    ? DashEditorCore.EditorConfig.theme.ConnectorInputConnectedColor
                    : DashEditorCore.EditorConfig.theme.ConnectorInputDisconnectedColor;

                if (IsExecuting)
                    GUI.color = Color.cyan;

                var connectorRect = GetConnectorRect(true, i);
                
                if (GUI.Button(connectorRect, "", skin.GetStyle(isConnected ? "NodeConnectorOn" : "NodeConnectorOff")))
                {
                    if (Event.current.button == 0)
                    {
                        if (Graph.connectingNode != null && Graph.connectingNode != this)
                        {
                            Undo.RegisterCompleteObjectUndo(_graph, "Connect node");
                            Graph.Connect(this, i, Graph.connectingNode, Graph.connectingOutputIndex);
                            DashEditorCore.SetDirty();
                            Graph.connectingNode = null;
                        }
                    }
                }
            }
            
            // Outputs
            for (int i = 0; i < OutputCount; i++)
            {
                bool isConnected = Graph.HasOutputConnected(this, i);
                GUI.color = isConnected
                    ? DashEditorCore.EditorConfig.theme.ConnectorOutputConnectedColor
                    : DashEditorCore.EditorConfig.theme.ConnectorOutputDisconnectedColor;

                if (Graph.connectingNode == this && Graph.connectingOutputIndex == i)
                    GUI.color = Color.green;

                var connectorRect = GetConnectorRect(false, i);
                
                if (connectorRect.Contains(Event.current.mousePosition - new Vector2(p_rect.x, p_rect.y)))
                    GUI.color = Color.green;

                if (OutputLabels != null && OutputLabels.Length > i && DashEditorCore.DetailsVisible)
                {
                    GUIStyle style = new GUIStyle();
                    style.normal.textColor = Color.white;
                    style.alignment = TextAnchor.MiddleRight;
                    GUI.Label(new Rect(connectorRect.x - 100, connectorRect.y, 100, 20), OutputLabels[i], style);
                }

                if (GUI.Button(connectorRect, "", skin.GetStyle(isConnected ? "NodeConnectorOn" : "NodeConnectorOff")))
                {
                    Graph.connectingOutputIndex = i;
                    Graph.connectingNode = this;
                }
            }

            GUI.color = Color.white;
        }
示例#45
0
        public void Setup()
        {
            var graph = new Graph("AB5,BC4,CD8,DC8,DE6,AD5,CE2,EB3,AE7");

            railroadUtils = new RailroadUtils("AB5,BC4,CD8,DC8,DE6,AD5,CE2,EB3,AE7");
        }
示例#46
0
 /// <summary>
 ///
 /// </summary>
 public void Initialize(Graph graph)
 {
     _graph         = graph;
     _vertexObjs    = new List <V>(_graph.VertexCount);
     _tensegrityObj = new List <TensegrityObject>(_graph.VertexCount);
 }
示例#47
0
 public Search(Graph G, int s)
 {
 }
示例#48
0
 public static GraphNode <Tile> GetLeft(this Graph <Tile> graph, GraphNode <Tile> node)
 {
     return(node.GetAllAdjacent().FirstOrDefault(x => x.Value.X - node.Value.X == -1));
 }
示例#49
0
 public ParallelSolver(SolverOptions options, Graph graph) : base(options, graph)
 {
 }
        static void Main(string[] args)
        {
            stack <int> s = new stack <int>();

            s.push(1);
            s.push(2);
            s.push(3);
            int element = s.pop();

            Console.WriteLine(element);
            element = s.pop();
            Console.WriteLine(element);
            s.push(4);

            Queue <int> q = new Queue <int>();

            q.enqueue(1);
            q.enqueue(2);
            q.enqueue(3);
            element = q.dequeue();
            element = q.dequeue();
            element = q.dequeue();
            element = q.dequeue();

            QueueWith2Stack qs = new QueueWith2Stack();

            qs.enqueue(1);
            qs.enqueue(2);
            element = qs.dequeue();
            element = qs.dequeue();

            //circular queue

            circularQueue <int> cq = new circularQueue <int>(3);

            cq.enqueue(1);
            cq.enqueue(2);
            cq.enqueue(3);
            cq.enqueue(4);
            element = cq.dequeu();
            element = cq.dequeu();


            LinkedList l  = new LinkedList();
            node <int> l1 = new node <int>(5);
            node <int> l2 = new node <int>(6);
            node <int> l3 = new node <int>(7);
            node <int> l4 = new node <int>(8);
            node <int> l5 = new node <int>(10);
            node <int> l6 = new node <int>(11);
            node <int> l7 = new node <int>(12);
            node <int> l8 = new node <int>(13);
            node <int> l9 = new node <int>(14);

            node <int> l10 = l3;

            // node<int> l7 = new node<int>(8);
            l.Add(l1); l.Add(l2); l.Add(l3); l.Add(l4); l.Add(l5); l.Add(l6); l.Add(l7); l.Add(l8); l.Add(l9); l.Add(l10);
            //l.Add(new node<int>(6));
            //l.Add(new node<int>(7));
            //l.Add(new node<int>(8));

            l.IsloopExist();


            //nth node from last
            LinkedList ll  = new LinkedList();
            node <int> ll1 = new node <int>(5);
            node <int> ll2 = new node <int>(6);
            node <int> ll3 = new node <int>(7);
            node <int> ll4 = new node <int>(8);
            node <int> ll5 = new node <int>(9);
            node <int> ll6 = new node <int>(10);
            node <int> ll7 = new node <int>(11);

            ll.Add(ll1); ll.Add(ll2); ll.Add(ll3); ll.Add(ll4); ll.Add(ll5); ll.Add(ll6); ll.Add(ll7);
            DeleteNthElementFromLastLinkedList nthlast = new DeleteNthElementFromLastLinkedList();

            nthlast.GetNthFromLast(ll.head, 3);

            // Delete nth nod
            nthlast.DeleteNthFromLast(ll.head, 3);//delete 9
            nthlast.traverse(ll.head);

            //Drawing BST
            //                   6
            //          2                11
            //      1       4        8       12
            //            3   5    7   9        13
            //                           10

            BinaryTree btree = new BinaryTree();

            btree.insert(new Bnode <int>(6));
            btree.insert(new Bnode <int>(11));
            btree.insert(new Bnode <int>(8));
            btree.insert(new Bnode <int>(12));
            btree.insert(new Bnode <int>(2));
            btree.insert(new Bnode <int>(1));
            btree.insert(new Bnode <int>(4));
            btree.insert(new Bnode <int>(13));
            btree.insert(new Bnode <int>(5));
            btree.insert(new Bnode <int>(3));
            btree.insert(new Bnode <int>(7));
            btree.insert(new Bnode <int>(9));
            btree.insert(new Bnode <int>(10));



            PrintAllPathBinaryTree PPath = new PrintAllPathBinaryTree();

            PPath.PrintPathRootToLeaf(btree.root);

            //Convert tree in doubly linked list ( this program shoule be commented out to run)
            //BinaryTreeToDoublyLinkedList b2ddl = new BinaryTreeToDoublyLinkedList();
            //b2ddl.ConvertB2DDL(btree.root);


            //Sub Tree
            BinaryTree subtree = new BinaryTree();
            //subtree.insert(new bnode<int>(4));
            //subtree.insert(new bnode<int>(3));
            //subtree.insert(new bnode<int>(5));


            SubTree progIsSubTree = new SubTree();
            Boolean issubtree     = progIsSubTree.FindSubTree(btree.root, subtree.root);

            var twosum = new _2Sum();

            twosum.TwoSumK(new int[] { 1, 4, 3, 5, 9, 2, 7 }, 6);


            //IsBalanced or Not ( ans not balanced, if you want balanced ans, then
            // Please remove node 5 and 3

            IsBalancedBinaryTree balancedTree = new IsBalancedBinaryTree();
            Boolean ansbalanced = balancedTree.Isbalanced(btree.root);

            //find Kth smallest element in binary search tree
            KthSmallelementBinarySearchTree kelement = new KthSmallelementBinarySearchTree();

            kelement.inorder(btree.root);

            //in-order with recursion
            btree.inorderTraverse(btree.root);

            //In-Order Traversal without recuriosn using stack
            Console.WriteLine("In-Order Traversal without recuriosn using stack");
            BinaryTreeInOrderWithoutRecursion prog = new BinaryTreeInOrderWithoutRecursion();

            prog.InorderTraversalUsingStack(btree.root);

            Console.WriteLine("All the Leaf nodes of Btree");
            //btree.printleafnodes(btree.root);
            LeafOrBoundryofBinaryTree binaryTree = new LeafOrBoundryofBinaryTree();

            binaryTree.printleafnodes(btree.root);

            Console.WriteLine("All the Left Edge nodes of Btree");
            //btree.printleftEdge(btree.root);
            binaryTree.printleftEdge(btree.root);

            Console.WriteLine("All the right Edge nodes of Btree");
            //btree.printrightEdge(btree.root);
            binaryTree.printrightEdge(btree.root);

            Console.WriteLine("Print Outer Edges of a Btree");
            //btree.printouterMostEdge(btree.root);
            binaryTree.printouterMostEdge(btree.root);

            //Print lowest common Ancestor in Binary Search Tree
            Bnode <int> LCA = btree.findCommonAncestor(btree.root, new Bnode <int>(13), new Bnode <int>(10));

            Console.WriteLine("Print lowest common Ancestor in Binary Search Tree:" + LCA.data);
            int height = btree.findHeight(btree.root);

            //print lowest common Ancestor in Binary Tree
            LowestCommonAncesstorBinaryTree blca = new LowestCommonAncesstorBinaryTree();

            LCA = blca.FindLCA(btree.root, new Bnode <int>(13), new Bnode <int>(10));
            Console.WriteLine("Print lowest common Ancestor in Binary Tree:" + LCA.data);

            //print out order level Btree
            Console.WriteLine("Print order-level binary tree");
            btree.printOrderLevelBtree(btree.root);

            //Construct a binary tree
            List <int> preOrder = new List <int>()
            {
                1, 2, 4, 8, 9, 10, 11, 5, 3, 6, 7
            };
            List <int> InOrder = new List <int>()
            {
                8, 4, 10, 9, 11, 2, 5, 1, 6, 3, 7
            };
            Bnode <int> root1 = BinaryTree.ConstructBinaryTree(preOrder, InOrder);

            Console.WriteLine("BTree Construction test by InOrder Traversal");
            btree.inorderTraverse(root1);

            //Find Ceiling Value form BST
            BinaryTree btree2 = new BinaryTree();

            btree2.insert(new Bnode <int>(8));
            btree2.insert(new Bnode <int>(4));
            btree2.insert(new Bnode <int>(12));
            btree2.insert(new Bnode <int>(2));
            btree2.insert(new Bnode <int>(6));
            btree2.insert(new Bnode <int>(10));
            btree2.insert(new Bnode <int>(14));
            int ceil = btree2.FindCeiling(btree2.root, 1);

            //btree2.BSTwithNeighbourPointers(btree2.root);

            //------------------IsBinary Search Tree------------------
            IsBST btreeIsBst = new IsBST();

            btreeIsBst.IsBinarySearchTree(btree2.root);


            //Two Array Merge
            int?[] arrA = new int?[] { 2, 4, 6, 8, 13 }; //Small Array
            int?[] arrB = new int?[13] {
                -1, 3, 5, 7, 9, 11, 12, null, null, null, null, null, null
            };                                                                                //big Array

            MergeTwoSortedArrays mat = new MergeTwoSortedArrays(arrA, arrB);

            mat.Merge();

            int?[] B = new int?[] { 1, 3, 5, 13, 15, 17 };
            int?[] A = new int?[] { 2, 4, 5, 8, 10, 11 };
            mat = new MergeTwoSortedArrays(A, B);
            //This operation Median finding applicable if both A and B are same size.
            mat.MergeOperation();

            int?med = mat.MedianCoparision(A, B);

            for (int i = 0; i < B.Length; i++)
            {
                Console.WriteLine(B[i].ToString());
            }

            //Find Celebrity

            //List<person> persons= new List<person>();
            //persons.Add( new person(1, new int[] { 2,3,4 }));
            //persons.Add( new person(2, new int[] { 1,3,4 }));
            //persons.Add(  new person(3, new int[] { 1,4 }));
            //persons.Add(  new person(4, new int[] {}));
            //persons.Add(  new person(5, new int[] { 2, 4 }));

            CelebrityProblem c = new CelebrityProblem();
            //person p = c.findCelebrity(persons);

            StringReversalinPlace_and_Recursion pg = new StringReversalinPlace_and_Recursion("ABCD");
            string reverse = pg.ReverseStringRecursion("ABCDEF");

            pg.ReverseString();


            //max sum subsequence
            int[]             e  = new int[] { 4, -9, 3, -2, 4, -12 };
            MaxSubSequenceSum m1 = new MaxSubSequenceSum(e);

            m1.GetMaxSubSequenceSum();
            m1.GetMaxSubSequenceSumDynamicprog();

            e = new int[] { -1, 0, 2, -1, 1, 0, -2 };
            PositivNegativZeroSort NZP = new PositivNegativZeroSort(e);

            NZP.sortNPZ();


            //find duplicates
            FindDuplicates fd = new FindDuplicates();

            int[] arr = new int[] { 1, 2, 3, 1, 3, 0, 6 };
            fd.findDup(arr);

            //Permutation
            PermutationAlgo pe = new PermutationAlgo();

            pe.permutationAlgo("", "ABCD");

            pe.PrintAllPermutations(new int[] { 1, 2 });


            //find purmutation to find anagram
            FindAnagramUsePermutation per = new FindAnagramUsePermutation("ABCD");

            per.permutation("", "ABCD");

            Console.WriteLine("-----------------------");
            char[] c1 = new char[] { 'A', 'B' };
            per.purmutUsingSwap(c1, c1.Length);
            //foreach (char[] c2 in per.str)
            //{
            //    for (int i = 0; i < c2.Length; i++)
            //    {
            //        Console.Write(c2[i]);
            //    }
            //    Console.WriteLine("");
            //}

            int[] arr3 = new int[12] {
                1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5
            };
            FindTheNumberOfOccurencesInSortedArray fnc = new FindTheNumberOfOccurencesInSortedArray();

            fnc.FindNumberOfOccurnece(arr3);

            //------------------- Shuffule Random Numbers -----------------
            ShuffleNumbers num = new ShuffleNumbers();

            int[] shuffledNum = num.shuffleNumbers();

            //--------------------Balanced Parantheses Test Case --------------
            balancedparentheses exp = new balancedparentheses("{{[[()]]}}}");
            Boolean             b   = exp.IsBalanced();

            exp = new balancedparentheses("]]}}}");
            b   = exp.IsBalanced();
            exp = new balancedparentheses("{[[(]]]}}");
            b   = exp.IsBalanced();

            //---------------Reverse a Linked List ----------------------
            //linked list for test
            LinkedList list = new LinkedList();
            node <int> n1   = new node <int>(5);
            node <int> n2   = new node <int>(6);
            node <int> n3   = new node <int>(7);
            node <int> n4   = new node <int>(8);
            node <int> n5   = new node <int>(10);

            list.Add(n1); list.Add(n2); list.Add(n3); list.Add(n4); list.Add(n5);

            ReverseLinkedList revList = new ReverseLinkedList();

            //iterative reverse linked list
            node <int> reversedList = revList.ReverseIterative(list.head);


            //Recursion reverse linked list
            node <int> head = null;

            revList.RecursiveReverseLinkedList(list.head, null);


            //--------------------------Permutation---------------------

            PermutationAlgo perm = new PermutationAlgo();

            perm.Permutation(new char[] { 'A', 'B', 'C' }, 0, 3);

            //-------------------SubArray Sum K --------------------------

            SubArraySumK sum = new SubArraySumK();

            sum.SubArraySumk(new int[] { 15, 2, 4, 8, 9, 5, 10, 23 }, 23);


            //------------------Find pair whoses sum is given number K in sorted array -----------------
            int[] sorted = new int[] { -8, 1, 4, 6, 8, 8, 10, 45 };
            FindSumOfTwoElementsGivenNumber pairK = new FindSumOfTwoElementsGivenNumber();

            pairK.findKsumPair(sorted, 16);
            //answer is multiple pair 6+10 and 8+8;

            //------------------------ Below two techniques are in place removal and compression tech------

            //------------------Remove Duplicates in sorted array and in space -------
            sorted = new int[] { -8, 1, 1, 2, 3, 3, 3, 4, 4, 5, 5 };
            Remove_Duplicates_from_Sorted_Array removeDup = new Remove_Duplicates_from_Sorted_Array();

            removeDup.RemoveDuplicatesFromSortedArray(sorted);
            //answer is sorted array itself = -8,1,2,3,4,5, |3,4,4,5,5| ( extran elements remove)

            //------------------Compress the sorted String [aBBBAAAaaa] compress to a1B2A3 ( in place)----
            char[] compressStr = new char[] { 'a', 'B', 'B', 'B', 'A', 'A', 'A', 'a', 'a', 'a' };
            removeDup.CompressString(compressStr);

            //------------------Find First non-Repeating Character------------------------------------

            FirstNonRepeatingCharacter fnrc = new FirstNonRepeatingCharacter();
            char nonrepeat = fnrc.FindFirstNonRepCh("abcbdeafcf");

            //------------Multiplication Recursion----------------
            int ans = new MultiplicationRecursion().Mul(2, 4);

            Console.WriteLine("Mul {0}", ans);


            //------------ Successor and Predessor -------------//

            BinaryTree BSuc = new BinaryTree();

            BSuc.insert(new Bnode <int>(18));
            BSuc.insert(new Bnode <int>(20));
            BSuc.insert(new Bnode <int>(14));
            BSuc.insert(new Bnode <int>(24));
            BSuc.insert(new Bnode <int>(19));
            BSuc.insert(new Bnode <int>(25));
            BSuc.insert(new Bnode <int>(23));
            BSuc.insert(new Bnode <int>(22));
            BSuc.insert(new Bnode <int>(21));
            BSuc.insert(new Bnode <int>(16));
            BSuc.insert(new Bnode <int>(17));
            BSuc.insert(new Bnode <int>(15));
            BSuc.insert(new Bnode <int>(13));

            BSTSuccessorAndPredecessor suc = new BSTSuccessorAndPredecessor();
            Bnode <int> Successor          = suc.InOrderSuccesor(BSuc.root, new Bnode <int>(22));

            Console.WriteLine("Successor : {0}", Successor.data.ToString());

            Bnode <int> Predecessor = suc.InOrderPredecessor(BSuc.root, BSuc.root.left); //14

            Console.WriteLine("Predecessor : {0}", Predecessor.data.ToString());

            //Phone Number Print 1-800-COM-CAST to 18002662278



            //Base Converter (binary or 0-9 base works)
            ConvertNumToBase conv = new ConvertNumToBase();

            Console.WriteLine("\nDecimal to Binary");
            conv.BaseConverter(8, 2);

            Console.WriteLine("\nDecimal to Eight");
            conv.BaseConverter(16, 8);

            Console.WriteLine("\nDecimal to Hex");
            //Hexadecimal converter
            conv.HexaDecimalConverter(95, 16);

            //Binary To Decimal
            Console.WriteLine("\nBinary To Decimal");
            NumberConverter conver = new NumberConverter();

            conver.NumConverter("110", 2);

            //Alphabates(26base) system to Decimal
            Console.WriteLine("\nAlphabates(26base) system to Decimal");
            _26BaseToDecimal base26 = new _26BaseToDecimal();

            base26.lettersToDecimal("az", 26);

            base26.Decimaltoletters(52, 26);

            //BoogleGame
            TrieNode t = new TrieNode();

            t.Contains('a');

            //Merge Sort
            MergeSortProg merge = new MergeSortProg();

            int[] array          = new int[] { 2, 4, 1, 3, 8, 7, 9, 6, 5, 10 };
            int[] afterMergeSort = new int[10];
            afterMergeSort = merge.MergeSort(array);


            //Reverse words in a string
            ReverseWordsInString rw = new ReverseWordsInString();
            string rev = rw.ReverseWords("Anup Rao");

            rev = rw.ReverseWords("Anup; Rao..");//fail

            //Remove Alternate nodes in a linked list
            LinkedList alt    = new LinkedList();
            node <int> altl1  = new node <int>(1);
            node <int> altl2  = new node <int>(2);
            node <int> altl3  = new node <int>(3);
            node <int> altl4  = new node <int>(4);
            node <int> altl5  = new node <int>(5);
            node <int> altl6  = new node <int>(6);
            node <int> altl7  = new node <int>(7);
            node <int> altl8  = new node <int>(8);
            node <int> altl9  = new node <int>(9);
            node <int> altl10 = new node <int>(10);

            alt.Add(altl1); alt.Add(altl2); alt.Add(altl3); alt.Add(altl4); alt.Add(altl5); alt.Add(altl6); alt.Add(altl7); alt.Add(altl8); alt.Add(altl9); alt.Add(altl10);
            RemoveAlternateLinkedList altRnode = new RemoveAlternateLinkedList();
            //Console.WriteLine("\norigional\n");
            //altRnode.print(alt.head);
            //Console.WriteLine("\ndelte alternate iteratively\n");
            //altRnode.RemoveAlt(alt.head);
            //altRnode.print(alt.head);
            //Console.WriteLine("\ndelte alternate recursively\n");
            //altRnode.RemoveAltRecursive(alt.head);
            //altRnode.print(alt.head);

            swapAlternative swapalt = new swapAlternative();

            swapalt.swapAlternativeElements(alt.head);
            swapalt.SwapAlternateElementsRec(alt.head);
            altRnode.print(alt.head);


            ConvertNumToLinkedList cntl = new ConvertNumToLinkedList();

            cntl.NumToLinkedList(1234);

            //Sum Two linkedList
            LinkedList sumL  = new LinkedList();
            node <int> sumL1 = new node <int>(1);
            node <int> sumL2 = new node <int>(2);
            node <int> sumL3 = new node <int>(3);
            node <int> sumL4 = new node <int>(4);
            node <int> sumL5 = new node <int>(5);

            sumL.Add(sumL1); sumL.Add(sumL2); sumL.Add(sumL3); sumL.Add(sumL4); sumL.Add(sumL5);

            LinkedList sumLS  = new LinkedList();
            node <int> sumL12 = new node <int>(7);
            node <int> sumL22 = new node <int>(9);
            node <int> sumL32 = new node <int>(8);
            node <int> sumL42 = new node <int>(9);

            sumLS.Add(sumL12); sumLS.Add(sumL22); sumLS.Add(sumL32); sumLS.Add(sumL42);

            SumTwoLinkedList sumlink = new SumTwoLinkedList();

            sumlink.LinkedListsSum(sumL.head, sumLS.head);


            //Reverse string before X
            ReverseCharactersBeforeX revS = new ReverseCharactersBeforeX();

            int startIndex = -1;

            //string res = revS.ReverseX("abcx",ref startIndex);
            revS.ReverseX("abcxd", 0);

            //Regex parser
            RegexParser regexp = new RegexParser();

            regexp.Match("ab*ab", "abbbbab", 0, 0);
            regexp.Match("ab*ab", "aab", 0, 0);
            regexp.Match("ab*ab", "aab", 0, 0);
            regexp.Match("ab*ba", "abba", 0, 0);
            regexp.Match("ab*ba", "abbbaba", 0, 0);//fail
            regexp.Match("ab*ab", "ab", 0, 0);
            regexp.Match("ab*ab", "abbab", 0, 0);
            regexp.Match("ab*ab", "abbabb", 0, 0);

            //Matrix Spiral
            MatrixSpriral matrix = new MatrixSpriral();

            matrix.SpiralPrint(new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 }, new int[] { 11, 12, 13, 14, 10 } });

            //Rotation Count minimal
            RotationCount rc      = new RotationCount();
            int           minimal = rc.CalcRotationCount(new int[] { 4, 5, 6, 7, 1, 2, 3 });


            //Replace spaces with %20
            ReplaceSpaces replace = new ReplaceSpaces();

            replace.ReplaceSpacesInStr("Anup Devangbhai Rao");

            //Set zeros for rows and columns in Matrix
            ZeroEntireRowAndColumn Zmat = new ZeroEntireRowAndColumn();

            int[][] Zmatrix = new int[][] { new int[] { 1, 2, 3, 0 }, new int[] { 4, 0, 6, 5 }, new int[] { 7, 8, 9, 10 } };
            Zmat.printMatrix(Zmatrix);
            Zmat.SetZero(Zmatrix);

            //Find Num in Sorted Matrix
            FindNumInSortedMatrix fsm = new FindNumInSortedMatrix();

            int[][] smMat = new int[][] { new int[] { 1, 2, 8, 9 }, new int[] { 2, 4, 9, 12 }, new int[] { 4, 7, 10, 13 }, new int[] { 6, 8, 11, 15 } };

            Boolean find = fsm.FindNum(smMat, 7);

            //Rotate Array
            RotateArrayProg ra = new RotateArrayProg();

            int[] rotArr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
            //Naive Method
            ra.RotateArray(rotArr, 3);
            ra.printArray(rotArr);

            //Juggling Method
            ra.RotateJug(rotArr, 3);
            ra.printArray(rotArr);

            //Min Heap
            Heap h = new Heap(11);

            h.insert(17);
            h.insert(21);
            h.insert(18);
            h.insert(43);
            h.insert(19);
            h.insert(11);
            h.insert(26);
            h.insert(23);
            h.insert(13);
            h.insert(17);
            h.insert(12);

            //get min
            int min = h.GetMin();

            min = h.extractMin();

            //Find top k max number
            TopKMaxNumbers topk = new TopKMaxNumbers();

            topk.FindKMax(new int[] { 1, 5, 8, 10, 2, 11, 1, 6, 8, 7, 9 }, 4);

            //simple binary search algo
            BinarySearchAlgo bsearch = new BinarySearchAlgo();

            bsearch.BinarySearch(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 6);

            //Reverse Words
            ReverseWords rv = new ReverseWords();

            rv.ReverseString("I am Anup Rao");

            //Fibonaci Series
            FibonaciSeries fb = new FibonaciSeries();

            fb.Fib(7);

            fb.fibIteratively(7);

            //root to leaf sum path
            RootToLeafPathSum r2l = new RootToLeafPathSum();

            BinaryTree r2fsumTree = new BinaryTree();

            r2fsumTree.insert(new Bnode <int>(6));
            r2fsumTree.insert(new Bnode <int>(11));
            r2fsumTree.insert(new Bnode <int>(2));
            r2fsumTree.insert(new Bnode <int>(4));
            r2fsumTree.insert(new Bnode <int>(5));
            r2fsumTree.insert(new Bnode <int>(1));
            r2fsumTree.insert(new Bnode <int>(3));

            Boolean br2f = r2l.FindSumPath(r2fsumTree.root, 17);

            SerializeAndDeserializeBtree sdb = new SerializeAndDeserializeBtree();

            sdb.Serialize(r2fsumTree.root);

            char[]       darr = new char[] { '3', '1', '5', '#', '#', '#', '2', '4', '#', '#', '6', '#', '#' };
            Queue <char> srlq = new Queue <char>();

            srlq.enqueue('3'); srlq.enqueue('1'); srlq.enqueue('5'); srlq.enqueue('#'); srlq.enqueue('#');
            srlq.enqueue('#'); srlq.enqueue('2'); srlq.enqueue('4'); srlq.enqueue('#'); srlq.enqueue('#');
            srlq.enqueue('6'); srlq.enqueue('#'); srlq.enqueue('#');

            BinaryNode root = new BinaryNode();

            sdb.Desearlize(darr);

            var serilazeroot = sdb.Desearlize(darr, 0, srlq);

            //All continiousSequences
            var cmb = new Substrings();

            cmb.PrintAllSubstrings(new int[] { 1, 2, 3, 4 });

            //Anagram is solved by permuation

            //Longest palindromic subsequence
            longestPalindromSubSequence lps = new longestPalindromSubSequence();
            string lpsstr = "AAXAYBZBAMANA";

            Boolean[] res = new Boolean[lpsstr.Length];
            lps.LPS(lpsstr, 0, lpsstr.Length - 1, res);

            //test
            new test().func();

            //Random number
            RandomNumber r = new RandomNumber();

            int[] stream = new int[5] {
                1, 2, 3, 4, 5
            };
            for (int i = 0; i < stream.Length; i++)
            {
                int randomNum = r.SelectRandom(stream[i]);
                Console.WriteLine(randomNum);
            }

            //Design question asked by Microsoft

            // Movie        | director              | Actors

            // Matrix       |  Andy Wachowski       | Keanu Reeves
            // Matrix       |  Andy Wachowski       | Laurence Fishburne
            // Matrix       |  Andy Wachowski       | Carrie-Anne
            // Interstellar |  Christopher Nolan    | Matthew McConaughey
            // Interstellar |  Christopher Nolan    | Anne Hathaway
            // Inception    |  Christopher Nolan    | Leonardo DiCaprio
            // Inception    |  Christopher Nolan    | Joseph Gordon-Levitt
            // Inception    |  Christopher Nolan    | Ellen Page

            String[] data = new String[] { "Matrix       |  Andy Wachowski       | Keanu Reeves",
                                           "Matrix       |  Andy Wachowski       | Laurence Fishburne",
                                           "Matrix       |  Andy Wachowski       | Carrie-Anne",
                                           "Interstellar       |  Christopher Nolan       | Matthew McConaughey",
                                           "Interstellar       |  Christopher Nolan       | Anne Hathaway",
                                           "Inception       |  Christopher Nolan       | Leonardo DiCaprio",
                                           "Inception       |  Christopher Nolan       | Joseph Gordon-Levitt",
                                           "Inception       |  Christopher Nolan       | Ellen Page", };

            DesignQuestion dq = new DesignQuestion();

            dq.Read(data);


            RemoveDuplicatesFromString rdu = new RemoveDuplicatesFromString();

            rdu.RemoveDup("jdctndjmckp");

            rdu.RemoveDup("1.2AE.B/ab(231/.CB/A");


            ConnectedIsland island  = new ConnectedIsland();
            int             Islands = island.FindNumberOfIsland(new int[][] { new int[] { 1, 1, 0, 0, 0 },
                                                                              new int[] { 0, 1, 0, 0, 1 },
                                                                              new int[] { 1, 0, 0, 1, 1 },
                                                                              new int[] { 0, 0, 0, 0, 0 },
                                                                              new int[] { 1, 0, 1, 0, 1 } });

            Console.WriteLine("\n" + Islands);



            Set     set   = new Set();
            Boolean isset = set.IsSet(new int[] { 1, 3, 5, 6, 8, 23, 45 });

            isset = set.IsSet(new int[] { 1, 3, 5, 6, 8, 23, 23, 45 });

            int?[] setr = set.MergeIntoSet(new int[] { 1, 3, 8, 9, }, new int[] { 2, 4, 6, 8, 9, 10 });

            ShuffleLinkedList shufflell = new ShuffleLinkedList();
            LinkedList        sll       = new LinkedList()
            {
                head = new node <int>(1)
            };

            sll.Add(new node <int>(2));
            sll.Add(new node <int>(3));
            sll.Add(new node <int>(4));
            sll.Add(new node <int>(5));
            sll.Add(new node <int>(6));

            shufflell.Shuffle(sll);

            //Hashtable
            HashTableLinearProbing hashtbl = new HashTableLinearProbing(5);

            hashtbl.Put(1, "Anup");
            hashtbl.Put(2, "Dhaval");
            hashtbl.Put(3, "Hardik");
            hashtbl.Put(4, "Vishal");
            hashtbl.Put(1, "UpdateAnup");
            hashtbl.Put(5, "Kiran");
            hashtbl.Put(6, "Raina");
            hashtbl.Put(7, "Sehwag");
            hashtbl.Remove(4);

            PhoneDictionary pd = new PhoneDictionary();

            pd.printWords(new int[] { 2, 3, 4 }, 0, new char[3], 0);

            NumberToWords ntw = new NumberToWords();

            ntw.PrintNumberToWords(11);
            ntw.PrintNumberToWords(110);
            ntw.PrintNumberToWords(250);
            ntw.PrintNumberToWords(9999);
            ntw.PrintNumberToWords(999);
            ntw.PrintNumberToWords(500);

            Anagram anagram = new Anagram();

            anagram.FindAnagram("abcde", "acbed");
            anagram.FindAnagram("abacde", "acbedb");
            anagram.FindAnagram("abaecdef", "afacbede");

            Programs.MovingAverage ma = new Programs.MovingAverage();
            ma.NextAverage(1);
            ma.NextAverage(2);
            ma.NextAverage(3);
            ma.NextAverage(4);
            ma.NextAverage(5);
            ma.NextAverage(6);

            MoveZerosSolution mz = new MoveZerosSolution();

            mz.MoveZeros(new int[] { 0, 1, 0, 3, 12 });


            int cityWidth  = 5;
            int cityLength = 7;

            int[] xCordinates = { 2, 4 };
            int[] yCordinates = { 3, 7 };

            Programs.lockerlocation.printMatrix(cityWidth, cityLength, xCordinates, yCordinates);


            LongestRepeatedSubString lrs    = new LongestRepeatedSubString();
            String longestrepeatedSubstring = lrs.FindLongestRepeatedSubstring("banana");

            longestrepeatedSubstring = lrs.FindLongestRepeatedSubstring("geeksforgeeks");
            longestrepeatedSubstring = lrs.FindLongestRepeatedSubstring("atcgatcga");

            EditDistanceAlgo eda = new EditDistanceAlgo();

            int editD = eda.EditDistance("sunday", "saturday", "sunday".Length - 1, "saturday".Length - 1);

            //minimum coin change problem
            minimumcoinProblem mcp = new minimumcoinProblem();
            var minimumCoins       = mcp.MinCoins(new int[] { 1, 5, 10, 25 }, 35);

            DeletionDistanceProg dsg = new DeletionDistanceProg();

            dsg.DeletionDistance("thought", "sloughs", "thought".Length - 1, "sloughs".Length - 1);

            LongestPalindromicSubstring lpsubstring = new LongestPalindromicSubstring();

            lpsubstring.FindLongestPalindromicSubstring("forgeeksskeegfor");

            lpsubstring.FindLongestPalindromicSubstring("EDREPUBLIC");

            Graph g = new Graph();

            g.AddEdge("SFO", "LAX").AddEdge("LAX", "ATL").AddEdge("ATL", "DEN")
            .AddEdge("DEN", "BOS").AddEdge("BOS", "JFK")
            .AddEdge("JFK", "DEN").AddEdge("DEN", "PHL")
            .AddEdge("PHL", "DFW").AddEdge("DFW", "SEA")
            .AddEdge("SEA", "DEN").AddEdge("DEN", "HOU")
            .AddEdge("HOU", "MIA");

            g.DFT("SFO");

            TestBooking1 tb1 = new TestBooking1();

            tb1.DeltaEncoding(new int[] { 25626, 25757, 24367, 24267, 16, 100, 2, 7277 });

            SortedArrayToBSTProg sortedArrToBST = new SortedArrayToBSTProg();
            var sortedArr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            sortedArrToBST.SortedArrayToBST(sortedArr, 0, sortedArr.Length - 1);

            MergeIntervals mergeIntervals = new MergeIntervals();

            var Intervals = new List <MergeIntervals.Interval>();

            //[1,3],[2,6],[8,10],[15,18]

            Intervals.Add(new  MergeIntervals.Interval {
                startime = 1, endtime = 3
            });
            Intervals.Add(new  MergeIntervals.Interval {
                startime = 2, endtime = 6
            });
            Intervals.Add(new  MergeIntervals.Interval {
                startime = 8, endtime = 10
            });
            Intervals.Add(new  MergeIntervals.Interval {
                startime = 15, endtime = 18
            });

            mergeIntervals.FunMergeIntervals(Intervals);

            TopologicalSortig topologicalsortProg = new TopologicalSortig(6);

            topologicalsortProg.TopologicalSort();

            SubSetProb subsetprob = new SubSetProb();

            subsetprob.Subset(new int[] { 1, 2, 3 }, 0, new int[3], 0);

            FriendshipScore frdscore = new FriendshipScore();

            int[][] FrdMat = new int[][] { new int[] { 0, 1, 1, 1, 0, 0, 0 },
                                           new int[] { 1, 0, 0, 0, 1, 0, 0 },
                                           new int[] { 1, 0, 0, 1, 1, 0, 0 },
                                           new int[] { 1, 0, 1, 0, 0, 0, 1 },
                                           new int[] { 0, 1, 1, 0, 0, 1, 0 },
                                           new int[] { 0, 0, 0, 0, 1, 0, 1 },
                                           new int[] { 0, 0, 0, 1, 0, 1, 0 } };

            var friendscor = frdscore.FindScore(FrdMat, 0, new Boolean[7], 0, 0, 6);

            Console.WriteLine(friendscor);

            var lightGrid = new char[][] { new char[] { 'N', 'Y' }, new char[] { 'Y', 'N' }, new char[] { 'Y', 'N' } };

            var OriglightGrid = new char[][] { new char[] { 'N', 'Y' }, new char[] { 'Y', 'N' }, new char[] { 'Y', 'N' } };

            SwitchFlip switchflip = new SwitchFlip();
            var        minflip    = switchflip.MaxRowsLitup(lightGrid, 0, 0, new int[lightGrid[0].Length], int.MinValue, new Stack <int>(), int.MaxValue, OriglightGrid);

            Console.WriteLine(minflip);

            CardRemoval crm = new CardRemoval();

            crm.SubArraySumk1("MMMMMBRU23", 13);
            crm.SubArraySumk1("MMMMMMMMMM", 13);

            crm.SubArraySumk1("MMMMBUR23L", 13);
            crm.SubArraySumk1("BU68482BM6875RL5M9573R", 13);
            crm.SubArraySumk1("BRM262362UMMBR6262437892MUULB332", 13);
            crm.SubArraySumk1("MUR55662LL3MBBMM2235RMMBM253525MMLMMU", 13);
            crm.SubArraySumk1("L92L43MU5U879RB2RM3", 13);
            crm.SubArraySumk1("7879L4LRM24R46M2B3UR7U4256632UR738LB6MB8M959L5U895", 13);
            crm.SubArraySumk1("B8929LUBR6L247759UMM5M3M947LRB284R4256R36587U6833B", 13);
            crm.SubArraySumk1("BLLUMM29U883L2LLU9329LBLLULMM2LULMRR88UL2B", 13);

            MaxProfitRod rdm  = new MaxProfitRod();
            string       sfsf = "fsafs";

            string[] nums = sfsf.Split();



            rdm.FindMaxProfitCut(new int[] { 26, 103, 59 }, 1, 10);

            //DependancyProg progdpe = new DependancyProg();

            //string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Anup Rao\Desktop\r\System Dependencies v3.in.txt");

            //Dictionary<String, DependancyProg.Item> Itemlist = new Dictionary<String, DependancyProg.Item>();

            //foreach (var ln in lines)
            //{
            //    string[] w = ln.Split(' ');

            //    var cmd = w[0];

            //    if(cmd == "DEPEND")
            //    {
            //        var itms = new List<DependancyProg.Item>();


            //        DependancyProg.Item newitem = null;
            //        for(int i=2;i<w.Length;i++)
            //        {
            //            if (w[i] == string.Empty)
            //                continue;

            //            if (!Itemlist.ContainsKey(w[i].ToString()))
            //                newitem = new DependancyProg.Item { Name = w[i].ToString() };

            //            newitem = Itemlist[w[i].ToString()];


            //            itms.Add(newitem);

            //        }



            //        if (!Itemlist.ContainsKey(w[1].ToString()))
            //            newitem = new DependancyProg.Item { Name = w[1].ToString() };

            //        newitem = Itemlist[w[1].ToString()];

            //        progdpe.DependOn(new DependancyProg.Item {Name = w[1].ToString()},itms.ToArray());
            //    }

            //    if (cmd == "INSTALL")
            //    {
            //        progdpe.Install(new DependancyProg.Item { Name = w[1].ToString() });
            //    }

            //    if (cmd == "REMOVE")
            //    {
            //        progdpe.Remove(new DependancyProg.Item { Name = w[1].ToString() });
            //    }

            //}

            var testmy = new test();


            UperLowerCasePermutation ulcp = new UperLowerCasePermutation();

            ulcp.PermuteUpperLower("abc", new Boolean[3], 0);

            WordLadder wld = new WordLadder();
            // wld.Transform("hit", "cog");

            string slu = "00:01:07,400-234-090\n 00:05:01,701 - 080 - 080\n00:05:00,400 - 234 - 090";

            slu = "00:01:07,400-234-090\n00:05:01,701-080-080\n00:05:00,400-234-090";

            slu = "00:01:07,400-234-090\n00:05:01,701-080-080\n00:05:00,400-234-090\n00:01:07,301-080-081\n00:04:00,301-080-081\n00:01:00,301-080-081";
            programs.Interview.VistaPrint.SolutionF tf = new Interview.VistaPrint.SolutionF();
            tf.solution(slu);

            Programs.Facebook.DecodeDigitsProg decodedigit = new Programs.Facebook.DecodeDigitsProg();

            decodedigit.DecodeDigits(new int[] { 1, 2, 3 }, 0, new string[3], 0);

            decodedigit.DecodeDigits(new int[] { 1, 2, 3, 4 }, 0, new string[4], 0);

            new SortSegmentProg().sortSegments("AZQF013452BAB");

            IPAddressValidation ipadr = new IPAddressValidation();
            var len = new List <string> {
                "22.231.113.64",
                "22.231.113.164",
                "222.231.113.64",
                "1050:1000:1000:a000:5:600:300c:326b",
                "1050:1000:2000:ab00:5:600:300c:326a",
                "1051:1000:4000:abcd:5:600:300c:326b"
            };

            for (int i = 0; i < len.Count; i++)
            {
                if (ipadr.IsValidIPV4Address(len[i]))
                {
                    Console.WriteLine("IPv4");
                }
                else if (ipadr.IsValidIPV6Address(len[i]))
                {
                    Console.WriteLine("IPv6");
                }
                else
                {
                    Console.WriteLine("Neither");
                }
            }

            var uniqarraysum = new MinUniqeArraySum();

            uniqarraysum.FindMiniumUniqeArraySum(new int[] { 5, 2, 6, 3, 2, 9, 10, 4, 5, 2 });

            compression cpr = new compression();

            cpr.CompressString("aaaaabbbbbbbbbccccpqrstuv");

            var pc = new ProducerConsumerProb();

            Thread[] T = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                T[i] = new Thread(pc.Produce);
                T[i].Start();
            }
            for (int i = 0; i < 3; i++)
            {
                T[i] = new Thread(pc.Consume);
                T[i].Start();
            }


            var gp = new GenerateParantheses();

            gp.GenerateCombinationParentheses(3, 3, 3, "");

            var StrobogrammaticNumber = new StrobogrammaticNumber();
            var resstrobog            = StrobogrammaticNumber.StroboGrammaticNumberPattern(4);
            var resstrobog1           = StrobogrammaticNumber.StroboGrammaticNumberPattern(5);
            var resstrobog2           = StrobogrammaticNumber.StroboGrammaticNumberPattern(6);

            AmazonSlidingWindowK aswk = new AmazonSlidingWindowK();

            aswk.subStringsKDist("wawaglknagagwunagkwkwagl", 4);
            aswk.subStringsKDist("democracy", 5);

            PartitionSequenceNoCharacterAppear pscnca = new PartitionSequenceNoCharacterAppear();

            pscnca.LengthEachScene(new List <char> {
                'a', 'b', 'c', 'd', 'a', 'e', 'f', 'g', 'h', 'i', 'j', 'e'
            }, new List <int>(), 0);
            pscnca.LengthEachScene(new List <char> {
                'z', 'z', 'c', 'b', 'z', 'c', 'h', 'f', 'i', 'h', 'i'
            }, new List <int>(), 0);

            // pscnca.LengthEachScene(new List<char> { 'a', 'b', 'c', 'd', 'a', 'e', 'f', 'g', 'h', 'i', 'j', 'e' });

            Programs.Google.MaxProductSubArray mpsa = new Programs.Google.MaxProductSubArray();
            mpsa.MaxProductSubArrayFunc(new int[] { 2, 3, -4, 5, -3, -5 });


            var intPalindrom = new Programs.BitManipulation.IntegerPalindrom();

            //intPalindrom.IsIntPalindrom(9);

            intPalindrom.reverseBits(9);

            var numpower2 = new Programs.BitManipulation.NumPowerOf2OrNot();

            numpower2.isNumPower2(8);
            numpower2.isNumPower2(10);

            var graycode    = new Programs.BitManipulation.GrayCode();
            var graycodeRes = graycode.GrayCodeFunc(4);


            var MinSpaceWordBreak = new WordBreakProblem();
            var ansSpace          = MinSpaceWordBreak.MinSpaceWordBreak("ILikeFaceBookiceCream", 0, new Dictionary <string, string> {
                { "ice", "ice" }, { "Cream", "Cream" }, { "iceCream", "IceCream" }, { "I", "I" }, { "Like", "Like" }, { "Face", "Face" }, { "Book", "Book" }, { "FaceBook", "FaceBook" }
            });

            Console.WriteLine(ansSpace);

            Console.Read();
        }
示例#51
0
 public double Calculate(Graph <Vector2D> graph, int from, int to)
 {
     return(graph.GetNode(from).Value.DistanceToSquared(graph.GetNode(to).Value));
 }
示例#52
0
 public Search(Graph graph)
 {
     this.graph = graph;
 }
示例#53
0
        /// <summary>
        /// loads the data from the repository into the MSAGL graph.
        /// This uses the default graphing and displaying, instead of geometry graph (previous version),
        /// as I have been unable to get the arrows to work using geometry graph in the latest MSAGL.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvObjectList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                this.UseWaitCursor  = true;
                graphViewer.Enabled = true;

                // do the impact analysis and lineage if that makes sense
                // get the ID of the selected node
                string objectName = e.Node.Name;
                int    objectID   = 0;
                if (int.TryParse(objectName, out objectID))
                {
                    //create the normal graph.
                    Graph newGraph = new Graph(objectName, objectID.ToString());
                    newGraph.Attr.LayerDirection = GetDirection();

                    Dictionary <int, Node> idToNodeMap = new Dictionary <int, Node>();
                    // get a list of nodes that depend on us
                    IDictionary <int, List <int> > dependencies = dependencyGraph.GetDependencies(objectID, numberOutbound);

                    foreach (int dependency in dependencies.Keys)
                    {
                        if (idToNodeMap.ContainsKey(dependency) == false)
                        {
                            Node node = newGraph.AddNode(dependency.ToString());
                            if (dependency == objectID)
                            {
                                node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                            }
                            else
                            {
                                node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.White;
                            }
                            node.Attr.Color = Microsoft.Msagl.Drawing.Color.Blue;

                            node.LabelText       = String.Format("{0}\r\n{1}", objectIDToNameMap[dependency], objectIDToTypeMap[dependency]);
                            node.Label.FontColor = Microsoft.Msagl.Drawing.Color.Blue;
                            idToNodeMap.Add(dependency, node);
                        }
                    }

                    // add the edges
                    foreach (int currentNode in dependencies.Keys)
                    {
                        Node fromNode = idToNodeMap[currentNode];

                        List <int> directDependencies = dependencies[currentNode];

                        foreach (int directDependency in directDependencies)
                        {
                            if (idToNodeMap.ContainsKey(directDependency))
                            {
                                Node toNode = idToNodeMap[directDependency];
                                // add an edge
                                newGraph.AddEdge(fromNode.Id, toNode.Id);
                            }
                        }
                    }

                    IDictionary <int, List <int> > lineages = dependencyGraph.GetLineage(objectID, numberInbound);

                    foreach (int lineage in lineages.Keys)
                    {
                        if (idToNodeMap.ContainsKey(lineage) == false)
                        {
                            Node node = newGraph.AddNode(lineage.ToString());
                            if (lineage == objectID)
                            {
                                node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                            }
                            else
                            {
                                node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.White;
                            }
                            node.Attr.Color      = Microsoft.Msagl.Drawing.Color.Blue;
                            node.LabelText       = String.Format("{0}\r\n{1}", objectIDToNameMap[lineage], objectIDToTypeMap[lineage]);
                            node.Label.FontColor = Microsoft.Msagl.Drawing.Color.Blue;
                            idToNodeMap.Add(lineage, node);
                        }
                    }

                    // add the edges
                    foreach (int currentNode in lineages.Keys)
                    {
                        Node toNode = idToNodeMap[currentNode];

                        List <int> directLineages = lineages[currentNode];

                        foreach (int directLineage in directLineages)
                        {
                            if (idToNodeMap.ContainsKey(directLineage))
                            {
                                Node fromNode = idToNodeMap[directLineage];
                                // add an edge
                                newGraph.AddEdge(fromNode.Id, toNode.Id);
                            }
                        }
                    }

                    graphViewer.NeedToCalculateLayout = true;
                    graphViewer.Graph = newGraph;
                }
                else
                {
                    graphViewer.Graph = null;
                }
            }
            finally
            {
                this.UseWaitCursor = false;
            }
        }
示例#54
0
 void OnEnable()
 {
     m_Graph = target as Graph;
 }
示例#55
0
 public GraphEdge <T> AddEdge(Graph <T> graph, GraphEdge <T> edge)
 {
     graph.Edges.Add(edge);
     return(edge);
 }
        /// <summary>
        ///     Creates a graph for the function
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameter"></param>
        /// <param name="explain"></param>
        /// <returns></returns>
        public override Graph CreateGraph(InterpretationContext context, Parameter parameter, ExplanationPart explain)
        {
            Graph retVal = new Graph();

            StructureValue LocationStruct = context.FindOnStack(Target).Value as StructureValue;

            SiDistance location;
            SiSpeed    speed;

            if (LocationStruct != null)
            {
                IVariable locationField = LocationStruct.Val["Location"] as IVariable;
                location = new SiDistance((locationField.Value as DoubleValue).Val);
                IVariable speedField = LocationStruct.Val["Speed"] as IVariable;
                speed = new SiSpeed((speedField.Value as DoubleValue).Val, SiSpeed_SubUnits.KiloMeter_per_Hour);

                Function decelerationFactor = context.FindOnStack(DecelerationFactor).Value as Function;
                if (decelerationFactor != null)
                {
                    Surface DecelerationSurface = decelerationFactor.CreateSurface(context, explain);
                    if (DecelerationSurface != null)
                    {
                        AccelerationSpeedDistanceSurface accelerationSurface =
                            DecelerationSurface.createAccelerationSpeedDistanceSurface(double.MaxValue, double.MaxValue);

                        QuadraticSpeedDistanceCurve BrakingCurve = null;

                        try
                        {
                            BrakingCurve = EtcsBrakingCurveBuilder.Build_Deceleration_Curve(accelerationSurface, speed,
                                                                                            location);
                        }
                        catch (Exception e)
                        {
                            retVal.AddSegment(new Graph.Segment(0, double.MaxValue, new Graph.Segment.Curve(0, 0, 0)));
                        }

                        SiSpeed finalSpeed = new SiSpeed(GetDoubleValue(context.FindOnStack(EndSpeed).Value),
                                                         SiSpeed_SubUnits.KiloMeter_per_Hour);
                        for (int i = 0; i < BrakingCurve.SegmentCount; i++)
                        {
                            QuadraticCurveSegment segment = BrakingCurve[i];

                            SiSpeed endSpeed = Max(finalSpeed, segment.Get(segment.X.X1));

                            SiDistance endDistance;
                            if (endSpeed == finalSpeed)
                            {
                                // Ensures that a braking curve is calculated until the finalSpeed
                                // but not further than the end of the curve segment
                                SiSpeed tmp = Max(segment.Get(segment.X.X1),
                                                  endSpeed - new SiSpeed(0.001));
                                endDistance = segment.IntersectAt(tmp);
                            }
                            else
                            {
                                endDistance = segment.X.X1;
                            }

                            Graph.Segment newSegment = new Graph.Segment(
                                segment.X.X0.ToUnits(),
                                endDistance.ToUnits(),
                                new Graph.Segment.Curve(
                                    segment.A.ToSubUnits(SiAcceleration_SubUnits.Meter_per_SecondSquare),
                                    segment.V0.ToSubUnits(SiSpeed_SubUnits.KiloMeter_per_Hour),
                                    segment.D0.ToSubUnits(SiDistance_SubUnits.Meter)
                                    )
                                );
                            retVal.AddSegment(newSegment);

                            if (endSpeed == finalSpeed)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            return(retVal);
        }
示例#57
0
 internal override void SetGraph(Graph graph)
 {
 }
示例#58
0
 public GuiNodes(MainWindow mainWindow, Graph graph, GuiLines guiLines)
 {
     this.mainWindow = mainWindow;
     this.graph      = graph;
     this.guiLines   = guiLines;
 }
示例#59
0
        private Graph BuildVisualGraph(PipelineDiagnostics diagnostics)
        {
            var graph = new Graph($"{diagnostics.Name} (running={diagnostics.IsPipelineRunning})", $"g{diagnostics.Id}");

            switch (this.model.Config.LayoutDirection)
            {
            case Config.DiagnosticsVisualizationObjectConfiguration.GraphLayoutDirection.LeftToRight:
                graph.Attr.LayerDirection = LayerDirection.LR;
                break;

            case Config.DiagnosticsVisualizationObjectConfiguration.GraphLayoutDirection.TopToBottom:
                graph.Attr.LayerDirection = LayerDirection.TB;
                break;

            case Config.DiagnosticsVisualizationObjectConfiguration.GraphLayoutDirection.RightToLeft:
                graph.Attr.LayerDirection = LayerDirection.RL;
                break;

            case Config.DiagnosticsVisualizationObjectConfiguration.GraphLayoutDirection.BottomToTop:
                graph.Attr.LayerDirection = LayerDirection.BT;
                break;
            }

            graph.UserData             = diagnostics.Id;
            graph.Attr.BackgroundColor = Color.Transparent;
            var subpipelineNodes             = new Dictionary <int, PipelineDiagnostics.PipelineElementDiagnostics>();
            var connectorsWithinSubpipelines = new Dictionary <int, PipelineDiagnostics.PipelineElementDiagnostics>();
            var statsSelector = this.StatsSelector(false);

            // add nodes
            var nodes = diagnostics.PipelineElements.Select(n => n.Value).Where(n => !this.IsConnectorBridge(n));

            foreach (var node in nodes)
            {
                var vis = this.BuildVisualNode(node);
                if (node.Kind == PipelineDiagnostics.PipelineElementDiagnostics.PipelineElementKind.Subpipeline)
                {
                    vis.UserData = node.RepresentsSubpipeline;
                    subpipelineNodes.Add(node.RepresentsSubpipeline.Id, node);
                    foreach (var n in node.RepresentsSubpipeline.PipelineElements.Values.Where(n => n.Kind == PipelineDiagnostics.PipelineElementDiagnostics.PipelineElementKind.Connector))
                    {
                        connectorsWithinSubpipelines.Add(n.Id, n);
                    }
                }
                else if (node.Kind == PipelineDiagnostics.PipelineElementDiagnostics.PipelineElementKind.Connector)
                {
                    vis.Attr.Color     = this.ConnectorColor;
                    vis.Attr.FillColor = this.ConnectorColor;
                    vis.Attr.Shape     = Shape.Circle;
                    vis.LabelText      = string.Empty;
                }

                graph.AddNode(vis);
            }

            // add edges
            var selectedEdgeUpdated = false;

            foreach (var n in diagnostics.PipelineElements)
            {
                foreach (var i in n.Value.Receivers)
                {
                    if (i.Value.Source != null)
                    {
                        if (this.AddVisualEdge(i.Value.Source.PipelineElement.Id, n.Value.Id, i.Value, graph, statsSelector))
                        {
                            selectedEdgeUpdated = true;
                        }
                    }
                }
            }

            // add connectors
            foreach (var n in diagnostics.PipelineElements.Where(n => this.IsConnectorBridge(n.Value)))
            {
                // connector bridging to subpipeline?
                if (subpipelineNodes.TryGetValue(n.Value.ConnectorBridgeToPipelineElement.ParentPipeline.Id, out PipelineDiagnostics.PipelineElementDiagnostics subNode))
                {
                    // edges from connector source directly to bridge target (subpipeline)
                    var sub = graph.FindNode($"n{subNode.Id}");
                    if (sub != null)
                    {
                        foreach (var i in n.Value.Receivers)
                        {
                            if (i.Value.Source != null)
                            {
                                var source = graph.FindNode($"n{i.Value.Source.PipelineElement.Id}");
                                if (source != null)
                                {
                                    graph.AddPrecalculatedEdge(this.BuildVisualEdge(source, sub, i.Value, statsSelector));
                                }
                            }
                        }

                        // edges from connector bridge source (subpipeline) to connector targets
                        foreach (var o in n.Value.Emitters)
                        {
                            foreach (var t in o.Value.Targets)
                            {
                                var target = graph.FindNode($"n{t.Value.PipelineElement.Id}");
                                if (target != null)
                                {
                                    graph.AddPrecalculatedEdge(this.BuildVisualEdge(sub, target, t.Value, statsSelector));
                                }
                            }
                        }
                    }
                }
                else
                {
                    // connector bridging to parent graph
                    var connector = new Node($"n{n.Value.Id}");
                    connector.Attr.Color     = this.ConnectorColor;
                    connector.Attr.FillColor = this.ConnectorColor;
                    connector.Attr.Shape     = Shape.Circle;
                    connector.LabelText      = string.Empty;
                    graph.AddNode(connector);

                    // edges from connector to target node
                    foreach (var o in n.Value.Emitters)
                    {
                        foreach (var t in o.Value.Targets)
                        {
                            var target = graph.FindNode($"n{t.Value.PipelineElement.Id}");
                            if (target != null)
                            {
                                graph.AddPrecalculatedEdge(this.BuildVisualEdge(connector, target, t.Value, statsSelector));
                            }
                        }
                    }

                    // edges to connector from source node
                    foreach (var i in n.Value.Receivers)
                    {
                        if (i.Value.Source != null)
                        {
                            var source = graph.FindNode($"n{i.Value.Source.PipelineElement.Id}");
                            if (source != null)
                            {
                                graph.AddPrecalculatedEdge(this.BuildVisualEdge(source, connector, i.Value, statsSelector));
                            }
                        }
                    }
                }
            }

            // add direct connections from one subpipeline (connector) to another
            foreach (var c in connectorsWithinSubpipelines.Values)
            {
                if (c.ConnectorBridgeToPipelineElement != null)
                {
                    if (c.ConnectorBridgeToPipelineElement.ParentPipeline == diagnostics && c.ConnectorBridgeToPipelineElement.Receivers.Count == 1)
                    {
                        var i = c.ConnectorBridgeToPipelineElement.Receivers.Values.First();
                        if (i.Source != null && i.Source.PipelineElement.ParentPipeline == diagnostics && i.Source.PipelineElement.ConnectorBridgeToPipelineElement != null)
                        {
                            if (subpipelineNodes.TryGetValue(i.Source.PipelineElement.ConnectorBridgeToPipelineElement.ParentPipeline.Id, out PipelineDiagnostics.PipelineElementDiagnostics source) &&
                                subpipelineNodes.TryGetValue(c.ParentPipeline.Id, out PipelineDiagnostics.PipelineElementDiagnostics target))
                            {
                                if (this.AddVisualEdge(source.Id, target.Id, i, graph, statsSelector))
                                {
                                    selectedEdgeUpdated = true;
                                }
                            }
                        }
                    }
                }
            }

            if (!selectedEdgeUpdated && this.selectedEdgeId != -1)
            {
                // hide while in subpipeline
                this.SelectedEdgeDetails = string.Empty;
            }

            this.VisualizeHeatmap(graph);
            return(graph);
        }
    /// <summary>
    /// Creates a sample graph and introduces all important graph elements present in
    /// yFiles WPF.
    /// </summary>
    private void PopulateGraph() {
      #region Sample Graph creation

      ///////////////// New in this Sample /////////////////
      
      // Creates a node outside the initial content rectangle
      INode node4 = Graph.CreateNode(new PointD(-100, -100));
      ILabel outsiderLabel = Graph.AddLabel(node4, "Outside Initial Viewport");

      //////////////////////////////////////////////////////

      //////////// Sample node creation ///////////////////

      // Creates two nodes with the default node size
      // The location is specified for the _center_
      INode node1 = Graph.CreateNode(new PointD(50, 50));
      INode node2 = Graph.CreateNode(new PointD(150, 50));
      // Creates a third node with a different size of 80x40
      // In this case, the location of (360,380) describes the _upper left_
      // corner of the node bounds
      INode node3 = Graph.CreateNode(new RectD(360, 380, 80, 40));

      /////////////////////////////////////////////////////

      //////////// Sample edge creation ///////////////////

      // Creates some edges between the nodes
      IEdge edge1 = Graph.CreateEdge(node1, node2);
      IEdge edge2 = Graph.CreateEdge(node2, node3);

      /////////////////////////////////////////////////////

      //////////// Using Bends ////////////////////////////

      // Creates the first bend for edge2 at (400, 50)
      IBend bend1 = Graph.AddBend(edge2, new PointD(400, 50));

      /////////////////////////////////////////////////////

      //////////// Using Ports ////////////////////////////

      // Actually, edges connect "ports", not nodes directly.
      // If necessary, you can manually create ports at nodes
      // and let the edges connect to these.
      // Creates a port in the center of the node layout
      IPort port1AtNode1 = Graph.AddPort(node1, FreeNodePortLocationModel.NodeCenterAnchored);

      // Creates a port at the middle of the left border
      // Note to use absolute locations when placing ports using PointD.
      IPort port1AtNode3 = Graph.AddPort(node3, new PointD(node3.Layout.X, node3.Layout.GetCenter().Y));

      // Creates an edge that connects these specific ports
      IEdge edgeAtPorts = Graph.CreateEdge(port1AtNode1, port1AtNode3);

      /////////////////////////////////////////////////////

      //////////// Sample label creation ///////////////////

      // Adds labels to several graph elements
      Graph.AddLabel(node1, "N 1");
      Graph.AddLabel(node2, "N 2");
      Graph.AddLabel(node3, "N 3");
      Graph.AddLabel(edgeAtPorts, "Edge at Ports");

      /////////////////////////////////////////////////////
      /////////////////////////////////////////////////////

      #endregion
    }