/// <summary>
        /// Обрабатывает событие нажатия на вершину.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnEllipseMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var ellipse = (VertexControl)sender;

            switch (_currentAction)
            {
            case InterfaceAction.VertexEdit:
                StartMovingVertex(ellipse);
                break;

            case InterfaceAction.EdgeEdit:
                CreateEdge(ellipse, e.GetPosition(Container));
                break;

            case InterfaceAction.PerformAlgorithm:
                if (_algorithmVerticesCount-- > 0)
                {
                    ColorizeVertices(new[] { _ellipses[ellipse] }, Brushes.Red);
                    _algorithmVertices.Add(_ellipses[ellipse]);
                }

                if (_algorithmVerticesCount == 0)
                {
                    var parameters = new GraphAlgorithmParameters(_graph, _algorithmVertices.ToArray());
                    _currentAlgorithm.PerformAlgorithmAsync(parameters);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemple #2
0
        public void SomeNewAlgorithmsTest()
        {
            var graph      = new Graph(1);
            var algorithm  = GraphAlgorithmFactory.ResolveGraphAlgorithm(GraphAlgorithmsRegistry.ExampleAlgorithm);
            var parameters = new GraphAlgorithmParameters(graph, edges: new Edge[] { });

            algorithm.PerformAlgorithmAsync(parameters);
            algorithm.AlgorithmPerformed += OnAlgorithmPerformed;
        }
Exemple #3
0
        protected override GraphAlgorithmResult PerformAlgorithm(GraphAlgorithmParameters parameters)
        {
            var graph = parameters.Graph;

            var eulerianPath = GraphAlgorithms.EulerianPath(graph);

            var stringResult = eulerianPath == null
                ? "Граф не содержит эйлеров путь"
                : $"Эйлеров путь:\n{string.Join("\n", eulerianPath)}";

            var result = new GraphAlgorithmResult(edges: eulerianPath?.ToArray(), stringResult: stringResult, isSequential: true);

            return(result);
        }
Exemple #4
0
        public void ConnectedComponentsCountTest()
        {
            var graph      = new Graph(3);
            var algorithm  = GraphAlgorithmFactory.ResolveGraphAlgorithm(GraphAlgorithmsRegistry.ConnectedComponentsCount);
            var parameters = new GraphAlgorithmParameters(graph);

            algorithm.PerformAlgorithmAsync(parameters);

            while (algorithm.IsPerforming)
            {
                Thread.Sleep(10);
            }

            algorithm.Result.Number.Should().Be(3);
        }
        protected override GraphAlgorithmResult PerformAlgorithm(GraphAlgorithmParameters parameters)
        {
            // Извлекаем из параметров нужные штуки
            var graph = parameters.Graph;

            // Вызываем написанный extension метод
            var connectedComponentsCount = GraphAlgorithms.ConnectedComponentsCount(graph);

            // Оборачиваем результат выполнения
            var result = new GraphAlgorithmResult(
                number: connectedComponentsCount,
                stringResult: $"Количество компонент связности: {connectedComponentsCount}");

            // Возвращаем
            return(result);
        }
        protected override GraphAlgorithmResult PerformAlgorithm(GraphAlgorithmParameters parameters)
        {
            // Извлекаем из параметров нужные штуки
            var graph = parameters.Graph;

            // Вызываем написанный extension метод
            var minimumSpanningTree = graph.MST()?.ToArray();

            var stringResult =
                minimumSpanningTree != null
                ? $"Минимальное остновное дерево:\n{string.Join<Edge>(Environment.NewLine, minimumSpanningTree.ToArray())}"
                : "Для данного графа невозможно построить минимальное остовное дерево";

            // Оборачиваем результат выполнения
            var result = new GraphAlgorithmResult(edges: minimumSpanningTree, stringResult: stringResult);

            // Возвращаем
            return(result);
        }
Exemple #7
0
        protected override GraphAlgorithmResult PerformAlgorithm(GraphAlgorithmParameters parameters)
        {
            // Извлекаем из параметров нужные штуки
            var graph = parameters.Graph;
            var begin = parameters.Vertices[0];
            var end   = parameters.Vertices[1];

            // Вызываем написанный extension метод
            var edgePath = graph.ShortestPath(begin, end)?.ToArray();

            var stringResult =
                edgePath != null
                ? $"Кратчайший путь:\n{string.Join<Edge>(Environment.NewLine, edgePath)}"
                : "Нет пути";

            // Оборачиваем результат выполнения
            var result = new GraphAlgorithmResult(edges: edgePath, stringResult: stringResult, isSequential: true);

            // Возвращаем
            return(result);
        }
        // TODO: алгоритм запускается в отдельном потоке, надо предусмотреть блокировку формы
        private void InitializeAlgorithmButtons()
        {
            var algorithms = GraphAlgorithmFactory.CreateAllGraphAlgorithms();
            var i          = 1;

            foreach (var algorithm in algorithms)
            {
                algorithm.Performed += result =>
                {
                    if (!string.IsNullOrWhiteSpace(result.StringResult))
                    {
                        MessageBox.Show(result.StringResult,
                                        GetStringResource("ResultMessageBoxTitle"));
                    }
                    else if (result.Number.HasValue)
                    {
                        MessageBox.Show(result.Number.ToString(),
                                        GetStringResource("ResultMessageBoxTitle"));
                    }

                    if (result.Edges != null)
                    {
                        if (result.IsSequential)
                        {
                            ColorizedEdgesAnimation(result.Edges, Brushes.Blue);
                        }
                        else
                        {
                            ColorizeEdges(result.Edges, Brushes.Blue);
                        }
                    }
                    if (result.Vertices != null)
                    {
                        ColorizeVertices(result.Vertices, Brushes.Red);
                    }
                    Dispatcher.Invoke(DispatcherPriority.Normal,
                                      (ThreadStart) delegate { ChangeAction(InterfaceAction.VertexEdit); });
                };
                var button = new Button
                {
                    Style   = FindResource("ToolbarButton") as Style,
                    Content = $"A{i++}",
                    ToolTip = algorithm.Name
                };
                button.Click += (sender, args) =>
                {
                    if (_currentAction == InterfaceAction.PerformAlgorithm && _algorithmVerticesCount == 0)
                    {
                        return;
                    }
                    ColorizeEdges(_graph.Edges, Brushes.Black);
                    ColorizeVertices(_graph.Vertices, Brushes.White);
                    ChangeAction(InterfaceAction.PerformAlgorithm);
                    _algorithmVertices = null;
                    foreach (var parametr in algorithm.RequiredParameters)
                    {
                        if (parametr.Item1 == typeof(Vertex))
                        {
                            _algorithmVerticesCount = parametr.Item2;
                            _algorithmVertices      = new List <Vertex>();
                        }
                    }

                    if (algorithm.RequiredParameters.Length == 1)
                    {
                        var parameters = new GraphAlgorithmParameters(_graph);
                        algorithm.PerformAlgorithmAsync(parameters);
                    }
                    _currentAlgorithm = algorithm;
                };
                Toolbar.Children.Add(button);
            }
        }