Exemple #1
0
        public void Test02()
        {
            int[][] successors = new int[][]
            {
                /* 0 */ new int[] { },
                /* 1 */ new int[] { 2, 4 },
                /* 2 */ new int[] { },
                /* 3 */ new int[] { 2, 5 },
                /* 4 */ new int[] { 2, 3 },
                /* 5 */ new int[] { 2, },
                /* 6 */ new int[] { 2, 7 },
                /* 7 */ new int[] { }
            };

            Func <int, IEnumerable <int> > succF = x => successors[x];
            var wasAcyclic = TopologicalSort.TryIterativeSort <int>(
                new[] { 1, 6 },
                i => succF(i).ToImmutableArray(),
                out var sorted
                );

            Assert.True(wasAcyclic);
            AssertTopologicallySorted(sorted, succF, "Test02");
            Assert.Equal(7, sorted.Length);
            AssertEx.Equal(new[] { 1, 4, 3, 5, 6, 7, 2 }, sorted);
        }
Exemple #2
0
        private void SortDependencyGraph()
        {
            OnProgress("Sorting dependency graph");
            var sort = new TopologicalSort <CodeUnit>(_rootUnit, parent => parent.Dependencies);

            _orderedUnitList = sort.Sort();
        }
Exemple #3
0
        public override void Produce(IEngineTask task)
        {
            Guard.AssertNotNull(task, "task");

            var dirtyNode = task.DirtyNode;

            Diagnostics.WriteLine(this,
                                  string.Format("scheduled task for node= {0}", dirtyNode.Node.Name));

            if (isInitialized)
            {
                task.CalculationOrder = topsortMap[dirtyNode.Vertex.Name];
            }
            else
            {
                // First time around we need to calculate (Update) all nodes
                // so here we sort the whole graph and use the visit order to
                // force calculation of everything.

                var graphSort = new TopologicalSort(engine.Graph);
                graphSort.Run();

                task.CalculationOrder = graphSort.VisitOrder;

                isInitialized = true;
            }

            SendNext(task);
        }
Exemple #4
0
            public void ReturnsEmptyListForCycle()
            {
                // Arrange
                var validators = new[]
                {
                    new ValidationConfigurationItem {
                        Name = "0", RequiredValidations = new List <string> {
                            "1"
                        }
                    },
                    new ValidationConfigurationItem {
                        Name = "1", RequiredValidations = new List <string> {
                            "2"
                        }
                    },
                    new ValidationConfigurationItem {
                        Name = "2", RequiredValidations = new List <string> {
                            "0"
                        }
                    },
                };

                // Act
                var actual = TopologicalSort.EnumerateAll(validators);

                // Assert
                Assert.Empty(actual);
            }
Exemple #5
0
        public void DoImport(Stream backupStream, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo      = new ExportImportProgressInfo();
            var membersTotalCount = 0;

            using (var streamReader = new StreamReader(backupStream))
                using (var reader = new JsonTextReader(streamReader))
                {
                    while (reader.Read())
                    {
                        if (reader.TokenType == JsonToken.PropertyName)
                        {
                            if (reader.Value.ToString() == "MembersTotalCount")
                            {
                                membersTotalCount = reader.ReadAsInt32() ?? 0;
                            }
                            else if (reader.Value.ToString() == "Members")
                            {
                                reader.Read();
                                if (reader.TokenType == JsonToken.StartArray)
                                {
                                    reader.Read();

                                    var members      = new List <Member>();
                                    var membersCount = 0;
                                    //TODO: implement to iterative import without whole members loading
                                    while (reader.TokenType != JsonToken.EndArray)
                                    {
                                        var member = _serializer.Deserialize <Member>(reader);
                                        members.Add(member);
                                        membersCount++;

                                        reader.Read();
                                    }
                                    //Need to import by topological sort order, because Organizations have a graph structure and here references integrity must be preserved
                                    var organizations             = members.OfType <Organization>();
                                    var nodes                     = new HashSet <string>(organizations.Select(x => x.Id));
                                    var edges                     = new HashSet <Tuple <string, string> >(organizations.Where(x => !string.IsNullOrEmpty(x.ParentId)).Select(x => new Tuple <string, string>(x.Id, x.ParentId)));
                                    var orgsTopologicalSortedList = TopologicalSort.Sort(nodes, edges);
                                    members = members.OrderByDescending(x => orgsTopologicalSortedList.IndexOf(x.Id)).ToList();
                                    for (int i = 0; i < membersCount; i += _batchSize)
                                    {
                                        _memberService.SaveChanges(members.Skip(i).Take(_batchSize).ToArray());

                                        if (membersTotalCount > 0)
                                        {
                                            progressInfo.Description = $"{ i } of { membersTotalCount } members imported";
                                        }
                                        else
                                        {
                                            progressInfo.Description = $"{ i } members imported";
                                        }
                                        progressCallback(progressInfo);
                                    }
                                }
                            }
                        }
                    }
                }
        }
        public void SearchContactsTest()
        {
            //
            // digraph G {
            //   "7"  -> "11"
            //   "7"  -> "8"
            //   "5"  -> "11"
            //   "3"  -> "8"
            //   "3"  -> "10"
            //   "11" -> "2"
            //   "11" -> "9"
            //   "11" -> "10"
            //   "8"  -> "9"
            // }

            var ret = TopologicalSort.Sort(
                new HashSet <int>(new[] { 1, 7, 5, 3, 8, 11, 2, 9, 10, 2 }),
                new HashSet <Tuple <int, int> >(
                    new[] {
                Tuple.Create(7, 11),
                Tuple.Create(7, 8),
                Tuple.Create(5, 11),
                Tuple.Create(3, 8),
                Tuple.Create(3, 10),
                Tuple.Create(11, 2),
                Tuple.Create(11, 9),
                Tuple.Create(11, 10),
                Tuple.Create(8, 9)
            }
                    )
                ).ToList();

            System.Diagnostics.Debug.Assert(ret.SequenceEqual(new[] { 1, 7, 5, 11, 2, 3, 8, 9, 10 }));
        }
Exemple #7
0
        public static Queue <MyInfo> PerformTopoSort(List <MyInfo> nodes)
        {
            var sorter = new TopologicalSort <MyInfo>();

            Queue <MyInfo> outQueue;

            foreach (var myInfo in nodes.Where(n => n.Checked))
            {
                if (myInfo.Dependencies.Any())
                {
                    foreach (var dependency in myInfo.Dependencies)
                    {
                        if (myInfo.Equals(dependency))
                        {
                            throw new Exception("Cyclic Dependency detected from '" + dependency + "' to '" + myInfo + "'");
                        }

                        sorter.Edge(myInfo, dependency);
                    }
                }
                else
                {
                    sorter.Edge(myInfo);
                }
            }

            sorter.Sort(out outQueue);

            return(outQueue);
        }
Exemple #8
0
        public void Process(bool runAsCoroutine = true, MonoBehaviour coroutineOwner = null)
        {
            m_coroutineOwner = coroutineOwner;
            ValidateDependencies();
            List <ITopologicalNode> list = new List <ITopologicalNode>();

            list = m_initActions.ConvertAll((Converter <InitAction, ITopologicalNode>)((InitAction obj) => obj));
            list.AddRange(m_completedActions.ConvertAll((Converter <CompletedInitAction, ITopologicalNode>)((CompletedInitAction obj) => obj)));
            list = TopologicalSort.Sort(list);
            list.RemoveAll((ITopologicalNode obj) => obj is CompletedInitAction);
            m_initActions = list.ConvertAll((ITopologicalNode obj) => obj as InitAction);
            EventDispatcher.AddListener <ActionCompleteEvent>(OnInitActionComplete);
            EventDispatcher.DispatchEvent(new InitStartEvent(InitActions.Count));
            if (CheckAllComplete())
            {
                OnAllInitComplete();
                return;
            }
            m_runAsCoroutine = runAsCoroutine;
            if (m_runAsCoroutine)
            {
                m_coroutineOwner.StartCoroutine(ExecuteReadyActionsCoroutine());
            }
            else
            {
                CoroutineHelper.RunCoroutineToCompletion(ExecuteReadyActionsCoroutine());
            }
        }
Exemple #9
0
        /// <summary>
        /// Calculate all cells in spreadsheet.
        /// </summary>
        /// <exception cref="SpreadsheetInternalException">Cyclic dependency found.</exception>
        public void Calculate()
        {
            IList <string> sortedKeys;

            try
            {
                sortedKeys = TopologicalSort.Sort(
                    GetAllKeys(),
                    key => GetCellByKey(key).CellDependencies.Where(d => CellInSpreadsheet(d))
                    );
            }
            catch (CyclicDependencyException exception)
            {
                throw new SpreadsheetInternalException($"Cannot calculate spreadsheet, there is cyclic dependencies between cells. {exception.Message}", exception);
            }

            foreach (var key in sortedKeys)
            {
                CalculateCell(GetCellByKey(key));
            }

            // Validate that all cells were calculated.
            foreach (var key in GetAllKeys())
            {
                if (GetCellByKey(key).CellState == CellState.Pending)
                {
                    throw new SpreadsheetInternalException($"The cell {key} was lost during the calculation.");
                }
            }
        }
Exemple #10
0
            public void ReturnsSingleResultForPath()
            {
                // Arrange
                var validators = new[]
                {
                    new ValidationConfigurationItem {
                        Name = "0", RequiredValidations = new List <string>()
                    },
                    new ValidationConfigurationItem {
                        Name = "1", RequiredValidations = new List <string> {
                            "0"
                        }
                    },
                    new ValidationConfigurationItem {
                        Name = "2", RequiredValidations = new List <string> {
                            "1"
                        }
                    },
                };

                // Act
                var actual = TopologicalSort.EnumerateAll(validators);

                // Assert
                var result = Assert.Single(actual);

                Assert.Equal(new List <string>()
                {
                    "0", "1", "2"
                }, result);
            }
        public void Test()
        {
            var graph1 = new DirectedWeightedGraph(false);

            for (int i = 'a'; i <= 'h'; i++)
            {
                graph1.AddVertex(Convert.ToString(Convert.ToChar(i)));
            }

            graph1.AddEdge("a", "b", 1);
            graph1.AddEdge("b", "c", 2);
            graph1.AddEdge("c", "d", 3);
            graph1.AddEdge("a", "g", 600);
            graph1.AddEdge("b", "f", 0);
            graph1.AddEdge("e", "b", 7);


            Stack <Vertex> stack = new Stack <Vertex>();

            stack.Push(graph1.GetVertex("d"));
            stack.Push(graph1.GetVertex("c"));
            stack.Push(graph1.GetVertex("f"));
            stack.Push(graph1.GetVertex("b"));
            stack.Push(graph1.GetVertex("g"));
            stack.Push(graph1.GetVertex("a"));
            stack.Push(graph1.GetVertex("e"));
            stack.Push(graph1.GetVertex("h"));

            var testStack = TopologicalSort <DirectedWeightedGraph> .Sort(graph1);

            for (int i = 'a'; i <= 'h'; i++)
            {
                Assert.AreEqual(stack.Pop(), testStack.Pop());
            }
        }
Exemple #12
0
        public void Process(Configurator configurator, bool runAsCoroutine = true)
        {
            if (configurator != null)
            {
                m_configurator = configurator;
            }
            Logger.LogDebug(this, "Starting to run init actions", Logger.TagFlags.INIT);
            ValidateDependencies();
            List <ITopologicalNode> list = new List <ITopologicalNode>();

            list          = m_initActions.ConvertAll((Converter <InitAction, ITopologicalNode>)((InitAction obj) => obj));
            list          = TopologicalSort.Sort(list);
            m_initActions = list.ConvertAll((ITopologicalNode obj) => obj as InitAction);
            EventDispatcher.AddListener <ActionCompleteEvent>(OnInitActionComplete);
            EventDispatcher.DispatchEvent(new InitStartEvent(InitActions.Count));
            if (CheckAllComplete())
            {
                OnAllInitComplete();
                return;
            }
            m_runAsCoroutine = runAsCoroutine;
            if (m_runAsCoroutine)
            {
                BaseGameController.Instance.StartCoroutine(ExecuteReadyActionsCoroutine());
            }
            else
            {
                CoroutineHelper.RunCoroutineToCompletion(ExecuteReadyActionsCoroutine());
            }
        }
Exemple #13
0
            public void ReturnsTwoResultsForTwoDisconnected()
            {
                // Arrange
                var validators = new[]
                {
                    new ValidationConfigurationItem {
                        Name = "0", RequiredValidations = new List <string>()
                    },
                    new ValidationConfigurationItem {
                        Name = "1", RequiredValidations = new List <string>()
                    },
                };

                // Act
                var actual = TopologicalSort.EnumerateAll(validators);

                // Assert
                actual = actual.OrderBy(x => string.Join(" ", x)).ToList();
                Assert.Equal(2, actual.Count);
                Assert.Equal(new List <string>()
                {
                    "0", "1"
                }, actual[0]);
                Assert.Equal(new List <string>()
                {
                    "1", "0"
                }, actual[1]);
            }
Exemple #14
0
        public List <string> GetTableOrderByDependencies()
        {
            //Chứa cặp các table và các dependency của chúng
            Dictionary <string, Item> existedAdj = new Dictionary <string, Item>();
            List <Item> graphTableDependency     = new List <Item>();

            List <string> tables = _dbUtilities.GetAllTable();

            foreach (var table in tables)
            {
                List <Item> adjTableDenpendencies = new List <Item>();
                //List các table dependency của table
                var dependencies = _dbUtilities.GetAllTableDependOn(table).ToArray();

                foreach (var dependency in dependencies)
                {
                    if (!table.Equals(dependency))               //Kiểm tra có phải là chính nó
                    {
                        if (!existedAdj.ContainsKey(dependency)) //Kiểm tra là đã tạo Item này chưa
                        {
                            var item = new Item(dependency);
                            existedAdj.Add(item.Name, item);
                        }
                        adjTableDenpendencies.Add(existedAdj[dependency]); //Tạo mới cạnh
                    }
                }
                //Tạo mới đỉnh là table các cạch là adjTableDenpendencies
                graphTableDependency.Add(new Item(table, adjTableDenpendencies.ToArray()));
            }

            return(TopologicalSort.Sort(graphTableDependency.ToArray(), x => x.Dependencies));
        }
Exemple #15
0
 private void CalculateReachableBlocks()
 {
     _reachableBlocks = new Dictionary <BasicBlock, HashSet <BasicBlock> >();
     foreach (var block in TopologicalSort.Sort(_basicBlocks, p => p.ExitBlocks, ignoreCycles: true))
     {
         _reachableBlocks[block] = CalculateReachableBlocks(block, new HashSet <BasicBlock>());
     }
 }
Exemple #16
0
        public static IEnumerable <Step <TCtx> > OrderRequiredFirst(DependencyGraphBuilder <Step <TCtx> > _graphBuilder, IEnumerable <Step <TCtx> > steps)
        {
            var sort     = new TopologicalSort <Step <TCtx> >();
            var unsorted = steps.ToList();
            var edges    = _graphBuilder.BuildDependencyGraph(unsorted).ToArray();

            return(sort.Sort(unsorted.ToList(), edges));
        }
        public IEnumerable <T> GetItemsInDependencyOrder(T source)
        {
            EnsureGraphIsAcyclic();

            var sort = new TopologicalSort <T, DependencyGraphNode <T> >(_adjacencyList.Clone(), source);

            return(sort.Result.Select(x => x.Value));
        }
        void CreateInitialOrderInLayers()
        {
            //the idea is to topologically ordering all nodes horizontally, by using vertical components, then fill the layers according to this order
            Dictionary <int, int> nodesToVerticalComponentsRoots = CreateVerticalComponents();
            IEnumerable <IntPair> liftedLeftRightRelations       = LiftLeftRightRelationsToComponentRoots(nodesToVerticalComponentsRoots).ToArray();

            int[] orderOfVerticalComponentRoots = TopologicalSort.GetOrderOnEdges(liftedLeftRightRelations);
            FillLayersWithVerticalComponentsOrder(orderOfVerticalComponentRoots, nodesToVerticalComponentsRoots);
            LayerArrays.UpdateXFromLayers();
        }
Exemple #19
0
        public void TopoTest_One()
        {
            TopologicalSort.Node        node  = new TopologicalSort.Node();
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                node
            };

            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.AreEqual(sortedNodes[0], nodes[0]);
        }
Exemple #20
0
        public void TopologicalSortForOneVertexGraph()
        {
            var sut = new TopologicalSort();

            var node1 = new GraphVertex <int>();

            var topologicalOrder = sut.GetTopologicalOrder(new[] { node1 });

            Assert.Single(topologicalOrder);
            Assert.Collection <int>(topologicalOrder, arg => Assert.Equal(0, arg));
        }
        public IEnumerable <Node <T> > Order()
        {
            if (_orderedRevisionVersion != _revisionVersion)
            {
                var sort = new TopologicalSort(this);
                orderedNodes            = sort.Order();
                _orderedRevisionVersion = _revisionVersion;
            }

            return(orderedNodes ?? new List <Node <T> >());
        }
        public void OrderedVertices_ShouldBe_abcdef()
        {
            var sorter   = new TopologicalSort <char, int>();
            var vertices = sorter.OrderedVertices(_graph);

            var sequence = string.Join("->", vertices.Select(v => v.Value));

            Console.WriteLine(sequence);

            sequence.Should().Be("A->B->C->E->F->D");
        }
Exemple #23
0
        /// <summary>
        /// Reorders Any WixSearch items.
        /// </summary>
        /// <param name="output">Output containing the tables to process.</param>
        private void ReorderWixSearch(Output output)
        {
            Table wixSearchTable = output.Tables["WixSearch"];

            if (null == wixSearchTable || wixSearchTable.Rows.Count == 0)
            {
                // nothing to do!
                return;
            }

            RowDictionary rowDictionary = new RowDictionary();

            foreach (Row row in wixSearchTable.Rows)
            {
                rowDictionary.AddRow(row);
            }

            Constraints constraints            = new Constraints();
            Table       wixSearchRelationTable = output.Tables["WixSearchRelation"];

            if (null != wixSearchRelationTable && wixSearchRelationTable.Rows.Count > 0)
            {
                // add relational info to our data...
                foreach (Row row in wixSearchRelationTable.Rows)
                {
                    constraints.AddConstraint((string)row[0], (string)row[1]);
                }
            }

            this.FindCircularReference(constraints);

            if (this.Core.EncounteredError)
            {
                return;
            }

            this.FlattenDependentReferences(constraints);

            // Reorder by topographical sort (http://en.wikipedia.org/wiki/Topological_sorting)
            // We use a variation of Kahn (1962) algorithm as described in
            // Wikipedia, with the additional criteria that start nodes are sorted
            // lexicographically at each step to ensure a deterministic ordering
            // based on 'after' dependencies and ID.
            TopologicalSort sorter    = new TopologicalSort();
            List <string>   sortedIds = sorter.Sort(rowDictionary.Keys, constraints);

            // Now, re-write the table with the searches in order...
            wixSearchTable.Rows.Clear();
            foreach (string id in sortedIds)
            {
                wixSearchTable.Rows.Add(rowDictionary[id]);
            }
        }
Exemple #24
0
        public void Test_is_graph_topological_sortable_for_non_cycle_case()
        {
            var edgeList = new int[3][];

            edgeList[0] = new[] { 1, 2 };
            edgeList[1] = new[] { 2, 3 };
            edgeList[2] = new[] { 3, 4 };
            var graph           = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(3, graph);

            Assert.True(topologicalSort.IsSortable());
        }
Exemple #25
0
        public void Test_Topological_Sorting()
        {
            var edgeList = new int[3][];

            edgeList[0] = new int[] { 1, 2 };
            edgeList[1] = new int[] { 2, 3 };
            edgeList[2] = new int[] { 3, 4 };
            var graph           = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(4, graph);

            Assert.Equal(new int[] { 4, 3, 2, 1 }, topologicalSort.Sort());
        }
Exemple #26
0
        public void Sort_DirectedGraphWithoutEdges_NothingToSort()
        {
            Dictionary <string, string[]> mock = new Dictionary <string, string[]>();

            mock.Add("A", new string[0]);
            mock.Add("B", new string[0]);
            mock.Add("C", new string[0]);

            var graphWithoutEdges = new[] { "A", "B", "C" };

            Assert.Equal(graphWithoutEdges, TopologicalSort.Sort(graphWithoutEdges, item => mock[item]));
        }
Exemple #27
0
 public void TopoTest_Circular()
 {
     TopologicalSort.Node a = new TopologicalSort.Node();
     TopologicalSort.Node b = new TopologicalSort.Node();
     a.Dependencies.Add(b);
     b.Dependencies.Add(a);
     List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
         a, b
     };
     // ReSharper disable once UnusedVariable
     List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);
 }
Exemple #28
0
 private static string GetValidationError(IReadOnlyList <ValidationConfigurationItem> validators, IReadOnlyList <string> cannotBeParallel)
 {
     try
     {
         TopologicalSort.Validate(validators, cannotBeParallel);
         return(null);
     }
     catch (ConfigurationErrorsException e)
     {
         return(e.Message);
     }
 }
Exemple #29
0
        public void TopoTest_NoDependencies()
        {
            TopologicalSort.Node        a     = new TopologicalSort.Node();
            TopologicalSort.Node        b     = new TopologicalSort.Node();
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                a, b
            };
            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.IsTrue(sortedNodes.Contains(a));
            Assert.IsTrue(sortedNodes.Contains(b));
        }
Exemple #30
0
        public static IEnumerable <T> OrderByDependencies <T>(this IEnumerable <T> items)
            where T : class
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            var nodes = items.Distinct().ToHashSet();
            var edges = items.SelectMany(GetEdges).Select(item => ToEdge(item.Item1, item.Item2, items)).ToHashSet();

            return(TopologicalSort.DestructiveOptimized(nodes, edges));
        }
        public static void Main()
        {
            var ts = new TopologicalSort<char>();
            Queue<char> outQueue;
            PriorityQueue<char> res= new PriorityQueue<char>();

            bool returnValue;

            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                char[] l = Console.ReadLine().ToCharArray();
                foreach (var p in l)
                {
                    res.Enqueue(p);
                }

                for (int j = 0; j < l.Length-1; j++)
                {
                    ts.Edge(l[j+1], l[j]);
                }

            }

            returnValue = ts.Sort(out outQueue);
            StringBuilder result = new StringBuilder();

            if (outQueue.Count == 0)
            {
               StringBuilder m = new StringBuilder();
                while (res.Count != 0)
                {
                    m.Append(res.Dequeue());
                }

                Console.WriteLine(m);
                return;
            }

            while (outQueue.Count != 0)
                result.Append(outQueue.Dequeue());
            Console.WriteLine(result);
        }
        public void SetNodesPosition(string graphText, string expectedPositions)
        {
            var graph = graphText.ToDirectedGraph<string, int>().ToDictionary(x => x.Key, x => x.Value);

            var algo = new TopologicalSort<string>(graph);
            algo.Run();

            foreach (var node in graph.Values) {
                Console.WriteLine(node.Id + " " + node.Value);
            }

            foreach (var nodePosition in expectedPositions.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)) {
                var pair = nodePosition.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
                var node = graph[pair[0].Trim()];
                int expectedPosition = int.Parse(pair[1]);

                Assert.That(node.Value, Is.EqualTo(expectedPosition), "Node '" + node.Id + "' has unexpected topological order.");
            }
        }
        /// <summary>
        /// Append the result of this dependency graph to the end of the given sorting solution
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public TopologicalSort CalculateSort(TopologicalSort instance)
        {
            HashSet<OrderedProcess> unused = new HashSet<OrderedProcess>(_processes);

            do
            {
                HashSet<OrderedProcess> set = new HashSet<OrderedProcess>(
                    unused.Where(p => !unused.Overlaps(p.Predecessors)) //select processes which have no predecessors in the unused set, which means that all their predecessors must either be used, or not exist, either way is fine
                );

                if (set.Count == 0)
                    throw new InvalidOperationException("Cannot order this set of processes");

                unused.ExceptWith(set);

                foreach (var subset in SolveResourceDependencies(set))
                    instance.Append(subset);
            }
            while (unused.Count > 0);

            return instance;
        }
Exemple #34
0
        public IEnumerable<Node> Order()
        {
            var order = new TopologicalSort();

            return order.Order(this);
        }
Exemple #35
0
        private void InitializeAlgorithms()
        {
            _firstPageAlgorithm = _algorithm;
            ExamPage secondPage = ExamPages[1];

            ObservableCollection<ComboboxElement> queue = new ObservableCollection<ComboboxElement>();

            switch (this.AlgorithmName)
            {
                case "Przeszukiwanie wszerz":
                    queue.Add( new ComboboxElement(0) );

                    _secondPageAlgorithm = new BFS(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue);
                    break;

                case "Przeszukiwanie w głąb":
                    _secondPageAlgorithm = new DFS(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes());
                    break;

                case "Sortowanie topologiczne":
                    _secondPageAlgorithm = new TopologicalSort(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue);
                    break;

                case "Algorytm Kruskala":
                    _secondPageAlgorithm = new Kruskal(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes());
                    break;

                case "Wykrywanie dwudzielności":
                    queue.Add(new ComboboxElement(0));

                    _secondPageAlgorithm = new Bipartition(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue);
                    break;

                case "Algorytm Dijkstry":
                    _secondPageAlgorithm = new Dijkstra(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes());
                    break;

                case "Algorytm Bellmana-Forda":
                    queue.Add(new ComboboxElement(0));

                    _secondPageAlgorithm = new BellmanFord(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue);
                    break;
            }
        }