Exemple #1
0
        public Retorno listarVerticesAresta(Aresta a)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            atualizarGrafo();

            Monitor.Exit(locker);

            List <Vertice> vertices = new List <Vertice>();

            Vertice vOrigem  = null;
            Vertice vDestino = null;

            vOrigem  = this.Vertices.Where(p => p.Nome == a.VerticeInicio).FirstOrDefault();
            vDestino = this.Vertices.Where(p => p.Nome == a.VerticeFim).FirstOrDefault();

            vertices.Add(vOrigem);
            vertices.Add(vDestino);

            //Serializado como uma lista de vertices
            retorno.Retorno_ = JsonConvert.SerializeObject(vertices);

            return(retorno);
        }
Exemple #2
0
        private void txtDescricaoAresta_Delete_LostFocus(object sender, RoutedEventArgs e)
        {
            if (txtDescricaoAresta_Delete.Text == "")
            {
                MessageBox.Show("Por favor informe a descrição da aresta!");
                return;
            }

            Retorno r = client.getGrafo();

            GrafoAtributo grafo = JsonConvert.DeserializeObject <GrafoAtributo>(r.Retorno_);

            Aresta a = null;

            a = grafo.Arestas.Where(p => p.Descricao == txtDescricaoAresta_Delete.Text).FirstOrDefault();

            if (a == null)
            {
                txtDescricaoAresta_Delete.Text = "";
                MessageBox.Show("A aresta informado não existe!!!");
            }
            else
            {
                txtDescricaoAresta_Delete.IsEnabled = false;

                txtVerticeOrigemAresta_Delete.Text        = a.VerticeInicio.ToString();
                txtVerticeDestinoAresta_Delete.Text       = a.VerticeFim.ToString();
                txtPesoAresta_Delete.Text                 = a.Peso.ToString();
                cbBidirecionalAresta_Delete.SelectedIndex = (a.FlagBidirecional == true ? 0 : 1);
            }
        }
        public Grafo ModelarGrafo(IList <Atomo> interfaceMolecular)
        {
            if (interfaceMolecular.Count.Equals(0))
            {
                throw new OperationCanceledException(
                          "A interface molecular está vazia. Operação cancelada."
                          );
            }

            var grafo = new Grafo
            {
                Vertices = new List <Atomo>(interfaceMolecular),
                Arestas  = new List <Aresta>()
            };

            foreach (var vertice in grafo.Vertices)
            {
                foreach (var atomo in interfaceMolecular)
                {
                    var distancia = vertice.CalcularDistanciaEuclidiana(atomo);

                    if (distancia <= 7)
                    {
                        var aresta = new Aresta(vertice, atomo);

                        if (!grafo.Arestas.Contains(aresta))
                        {
                            grafo.Arestas.Add(aresta);
                        }
                    }
                }
            }

            return(grafo);
        }
Exemple #4
0
        public Retorno deleteAresta(Aresta a)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            atualizarGrafo();

            Aresta aux = null;

            aux = this.Arestas.Where(p => p.Descricao == a.Descricao).FirstOrDefault();

            if (aux == null || !this.Arestas.Remove(aux))
            {
                Console.WriteLine("Não foi possível excluir a aresta!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível excluir a aresta!";
                return(retorno);
            }

            if (!Util.escreverGrafoArquivo(this, Util.caminho))
            {
                Console.WriteLine("Não foi possível excluir a aresta no arquivo!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível excluir a aresta no arquivo!";
                return(retorno);
            }

            Monitor.Exit(locker);

            Console.WriteLine("Aresta excluído com sucesso!");
            retorno.Mensagem = "Aresta excluído com sucesso!";

            return(retorno);
        }
Exemple #5
0
 private void ProcessaVeiculoSimulacao()
 {
     if (ImprimirLogTela)
     {
         Console.WriteLine("Iniciando rotina de Geração de veículos");
     }
     foreach (var rua in RuasSimulacao)
     {
         Aresta  ArestaCorrespondente = grafo.GetAresta(rua.IdAresta);
         Vertice VerticeOrigem        = grafo.GetVertice(ArestaCorrespondente.Origem);
         if (VeiculosEsperaVertice[ArestaCorrespondente.Origem].Count > 0)
         {
             if (rua.AdicionaVeiculo(VeiculosEsperaVertice[ArestaCorrespondente.Origem].Peek(), SegundoSimulacao))
             {
                 if (ImprimirLogTela)
                 {
                     Console.WriteLine($"O veículo {VeiculosEsperaVertice[ArestaCorrespondente.Origem].Peek().Id} entrou na rua {rua.Id}");
                 }
                 VeiculosEsperaVertice[ArestaCorrespondente.Origem].Dequeue();
             }
         }
         #region TrativaLogs
         LogOcupacaoVias.Add(new LogOcupacaoVias()
         {
             IdAresta      = rua.IdAresta,
             EspacoOcupado = (int)rua.MediaOcupacaoVias(),
             InstanteTempo = SegundoSimulacao
         });
         #endregion TrativaLogs
     }
 }
Exemple #6
0
        /* Instanciando o autômato na mão */
        static void Exemplo1()
        {
            var no1 = new Estado("1", false);
            var no2 = new Estado("2", false);
            var no3 = new Estado("3", false);
            var no4 = new Estado("4", false);
            var no5 = new Estado("5", true);

            var listaEstados = new List <Estado> {
                no1, no2, no3, no4, no5
            };

            /* Arestas do No1 */
            var aresta1 = new Aresta('a', no2);

            no1.Arestas.Add(aresta1);

            /* Arestas do No1 */
            var aresta2 = new Aresta('b', no1);
            var aresta3 = new Aresta('a', no3);
            var aresta4 = new Aresta('a', no4);

            no2.Arestas.Add(aresta2);
            no2.Arestas.Add(aresta3);
            no2.Arestas.Add(aresta4);

            /* Arestas do No3 */
            var aresta5 = new Aresta('b', no4);

            no3.Arestas.Add(aresta5);

            /* Arestas do No4 */
            var aresta6 = new Aresta('a', no5);

            no4.Arestas.Add(aresta6);

            var simbolosAceitos = new List <char> {
                'a', 'b'
            };

            var afn = new AFN(listaEstados, no1, simbolosAceitos);

            /* Função Pe */
            var resultado1 = VerificaPalavra("aab", afn);

            Console.WriteLine($"Palavra: aab -> {(resultado1 ? "ACEITA" : "NÃO ACEITA")}");

            var resultado2 = VerificaPalavra("baaa", afn);

            Console.WriteLine($"Palavra: baaa -> {(resultado2 ? "ACEITA" : "NÃO ACEITA")}");

            var resultado3 = VerificaPalavra("aaa", afn);

            Console.WriteLine($"Palavra: aaa -> {(resultado3 ? "ACEITA" : "NÃO ACEITA")}");

            var resultado4 = VerificaPalavra("abababaaa", afn);

            Console.WriteLine($"Palavra: abababaaa -> {(resultado4 ? "ACEITA" : "NÃO ACEITA")}");
        }
Exemple #7
0
        public void BuscarAdicionarDestino(Aresta a)
        {
            Vertice auxDestino = (Vertice)Buscar(a.Destino);

            if (auxDestino != null)
            {
                a.Destino.Arestas.Adicionar(a);
            }
        }
Exemple #8
0
        public void BuscarAdicionarOrigem(Aresta a)
        {
            Vertice auxOrigem = (Vertice)Buscar(a.Origem);

            if (auxOrigem != null)
            {
                a.Origem.Arestas.Adicionar(a);
            }
        }
Exemple #9
0
        /// <summary>
        /// Checks Add-combobox and confirms the operation
        /// </summary>
        /// <param name="sender">Button Confirm</param>
        /// <param name="e">Routed Event</param>
        private async void Confirm_add_item(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Graph_exist)
                {
                    switch (selected_item_name)
                    {
                    case "Vértice":
                    {
                        Vertice vertice_aux = new Vertice(label_box.Text, Graph.NumVertices());
                        Graph.AddVertice(vertice_aux);

                        v1_box.Items.Add(vertice_aux.Label);
                        v2_box.Items.Add(vertice_aux.Label);
                        v1_rem_box.Items.Add(vertice_aux.Label);
                        v2_rem_box.Items.Add(vertice_aux.Label);
                        if (Graph.Vertices.Count > 0)
                        {
                            Vertex_list.ItemsSource = Graph.VerticeToListString();
                        }
                        else
                        {
                            Vertex_list.ItemsSource = null;
                        }
                        IsNotRendered = true;
                        break;
                    }

                    case "Aresta":
                    {
                        if (Graph.Vertices.Count > 0)
                        {
                            Aresta aresta_aux = new Aresta(float.Parse(weigth_Aresta_box.Text), Graph.BuscaVertice(v1_box.SelectedItem.ToString()), Graph.BuscaVertice(v2_box.SelectedItem.ToString()), Graph.isDigraph);
                            Graph.AddAresta(aresta_aux);
                        }
                        break;
                    }
                    }
                    if (selected_item_name != "")
                    {
                        myConsole.AddStringToConsole($"\n{selected_item_name} {label_box.Text} foi adicionado.");
                    }
                    myConsole.Update();
                }
                else
                {
                    msgdi = new MessageDialog("Não existe Grafo ainda!");
                    await msgdi.ShowAsync();
                }
            }catch (Exception ex) {
                msgdi = new MessageDialog($"Erro {ex.Message}");
                await msgdi.ShowAsync();
            }
        }
Exemple #10
0
 public Aresta AddAresta(Vertice origem, Vertice destino, Int32 peso = 1)
 {
     if (vertices.Contains(origem) && vertices.Contains(destino))
     {
         Aresta e = new Aresta(origem, destino, peso);
         origem.AddArestaAdj(e);
         arestas.Add(e);
         return(e);
     }
     throw new Exception("Não é possivel criar arestas entre vértices que não pertençam ao grafo.");
 }
Exemple #11
0
        private void btnBuscarVerticesAresta_Click(object sender, RoutedEventArgs e)
        {
            if (txtDescricaoArestaBuscar.Text == "")
            {
                MessageBox.Show("Por favor informe a descrição da aresta a ser utilizada!");
                return;
            }

            Aresta a = new Aresta();

            a.Descricao = txtDescricaoArestaBuscar.Text;

            try
            {
                Uteis.startAguarde();

                //Verificar de forma ordenada em qual servidor está a aresta
                Retorno r = VariaveisGlobais.client_servidor1.listarVerticesAresta(a);

                if (!r.Sucesso)
                {
                    r = VariaveisGlobais.client_servidor2.listarVerticesAresta(a);

                    if (!r.Sucesso)
                    {
                        r = VariaveisGlobais.client_servidor3.listarVerticesAresta(a);

                        if (!r.Sucesso)
                        {
                            MessageBox.Show("A aresta informa não existe");
                            return;
                        }
                    }
                }

                List <Vertice> vertices = JsonConvert.DeserializeObject <List <Vertice> >(r.Retorno_);

                txtNomeVertice1.Text      = vertices[0].Nome.ToString();
                txtCorVertice1.Text       = vertices[0].Cor.ToString();
                txtDescricaoVertice1.Text = vertices[0].Descricao;
                txtPesoVertice1.Text      = vertices[0].Peso.ToString();

                txtNomeVertice2.Text      = vertices[1].Nome.ToString();
                txtCorVertice2.Text       = vertices[1].Cor.ToString();
                txtDescricaoVertice2.Text = vertices[1].Descricao;
                txtPesoVertice2.Text      = vertices[1].Peso.ToString();
            }catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }finally
            {
                Uteis.stopAguarde();
            }
        }
Exemple #12
0
        public Aresta[] GeraVetor()//Gerar um vetor com todas as arestas do grafo
        {
            Aresta[] vetor = new Aresta[Tamanho];
            Elemento aux   = pri.Prox;

            for (int i = 0; i < vetor.Length; i++)
            {
                vetor[i] = (Aresta)aux.Dados;
                aux      = aux.Prox;
            }
            return(vetor);
        }
Exemple #13
0
        private void btnLimparCamposUpdateAresta_Click(object sender, RoutedEventArgs e)
        {
            txtVerticeOrigemUpdateAresta.IsEnabled  = true;
            txtVerticeDestinoUpdateAresta.IsEnabled = true;
            txtVerticeOrigemUpdateAresta.Text       = "";
            txtVerticeDestinoUpdateAresta.Text      = "";
            txtDescricaoArestaUpdate.Text           = "";
            txtPesoArestaUpdate.Text = "";
            cbBidirecionalArestaUpdate.SelectedIndex = 1;

            arestaCorrente = null;
        }
Exemple #14
0
        private Grafo GerarGrafoBase(List <Vertice> vertices, out List <Aula> aulasSemHorario)
        {
            aulasSemHorario = new List <Aula>();
            List <Aula> aulasVazias = new List <Aula>();

            if (vertices == null)
            {
                return(new Grafo());
            }
            Grafo            grafo = new Grafo();
            List <DiaSemana> dias  = this.GerarDiasDaSemana();
            List <Aula>      aulas = new List <Aula>();
            DiaSemana        diaDisponivel;
            Aresta           aresta;
            Vertice          verticeDia;
            Vertice          verticeAula;
            int totalDiasRestantes = 0;

            this.AdicionarVerticesEmVerticeEListas(grafo, dias, aulas, vertices);
            grafo.AddVertice(Vertice.ConverterParaVertice(new List <IDado>(dias)));
            totalDiasRestantes = this.GetTotalDiasRestantesAulas(aulas);

            while (totalDiasRestantes > 0)
            {
                aulas.ForEach(aula =>
                {
                    if (aula.GetAulasPorSemanaRestante() > 0)
                    {
                        diaDisponivel = this.GetDiaDisponivelParaMateria(aula, dias);
                        if (diaDisponivel != null)
                        {
                            verticeDia  = grafo.GetVertice(diaDisponivel);
                            verticeAula = grafo.GetVertice(aula);

                            aresta = new Aresta(verticeDia, verticeAula, 0);

                            verticeDia.AddAresta(aresta);
                            verticeAula.AddAresta(aresta);
                            ((DiaSemana)verticeDia.GetDado()).AdicionarAula((Aula)verticeAula.GetDado());
                            aula.SetAulaAlocada(true);
                        }
                    }
                    else if (!aula.GetAulaAlocada())
                    {
                        aulasVazias.Add(aula);
                    }
                    aula.DiminuirAulasPorSemanasRestante();
                });
                totalDiasRestantes = this.GetTotalDiasRestantesAulas(aulas);
            }
            aulasSemHorario = aulasVazias;
            return(grafo);
        }
Exemple #15
0
        private void Aresta_Update_LostFocus(object sender, RoutedEventArgs e)
        {
            if (txtVerticeOrigemUpdateAresta.Text == "" || txtVerticeDestinoUpdateAresta.Text == "")
            {
                return;
            }

            //Vamos identificar qual client será utilizado
            int nClient = Uteis.GetServidor(txtVerticeOrigemUpdateAresta.Text);

            Retorno r = new Retorno();

            switch (nClient)
            {
            case 0:
                r = VariaveisGlobais.client_servidor1.getGrafo();
                break;

            case 1:
                r = VariaveisGlobais.client_servidor2.getGrafo();
                break;

            case 2:
                r = VariaveisGlobais.client_servidor3.getGrafo();
                break;
            }

            GrafoAtributo grafo = JsonConvert.DeserializeObject <GrafoAtributo>(r.Retorno_);

            Aresta a = null;

            a = grafo.Arestas.Where(p => p.VerticeInicio == Convert.ToInt32(txtVerticeOrigemUpdateAresta.Text) && p.VerticeFim == Convert.ToInt32(txtVerticeDestinoUpdateAresta.Text)).FirstOrDefault();

            if (a == null)
            {
                txtDescricaoArestaUpdate.Text = "";
                MessageBox.Show("A aresta informado não existe!!!");
            }
            else
            {
                txtVerticeOrigemUpdateAresta.IsEnabled  = false;
                txtVerticeDestinoUpdateAresta.IsEnabled = false;

                txtVerticeOrigemUpdateAresta.Text        = a.VerticeInicio.ToString();
                txtVerticeDestinoUpdateAresta.Text       = a.VerticeFim.ToString();
                txtDescricaoArestaUpdate.Text            = a.Descricao;
                txtPesoArestaUpdate.Text                 = a.Peso.ToString();
                cbBidirecionalArestaUpdate.SelectedIndex = (a.FlagBidirecional == true ? 0 : 1);

                arestaCorrente = a;
            }
        }
        protected override void OnInitialized()
        {
            Arestas   = new List <Aresta>();
            Vertices  = new List <Vertice>();
            Vertice   = new Vertice();
            Aresta    = new Aresta();
            Economias = new List <Economia>();

            InicializarCores();
            GerarDadosParaTeste();

            base.OnInitialized();
        }
Exemple #17
0
    public void AddArestaToShape(Aresta a)
    {
        ShapeAresta  are;
        ShapeVertice v1, v2;

        if (IsShaped(a.vertice1) && IsShaped(a.vertice2))
        {
            v1 = GetShape(a.vertice1);
            v2 = GetShape(a.vertice2);

            are = new ShapeAresta(v1, v2);
            Arestas.Add(are);
        }
    }
Exemple #18
0
        public Retorno updateAresta(Aresta a)
        {
            Retorno retorno = new Retorno(true);

            try
            {
                Monitor.Enter(VariaveisGlobais.lockerAresta);

                atualizarGrafo();

                Aresta aux = null;
                aux = this.Arestas.Where(p => p.Descricao == a.Descricao).FirstOrDefault();

                if (aux != null && this.Arestas.Remove(aux))
                {
                    this.Arestas.Add(a);
                }
                else
                {
                    VariaveisGlobais.telaPrincipal.AtualizarLog("Erro ao atualizar a aresta " + a.Descricao + "!");
                    retorno.Sucesso  = false;
                    retorno.Mensagem = "Erro ao atualizar a aresta!";
                    return(retorno);
                }

                if (!Uteis.escreverGrafoArquivo(this))
                {
                    VariaveisGlobais.telaPrincipal.AtualizarLog("Não foi possível atualizar a aresta " + a.Descricao + " no arquivo!");
                    retorno.Sucesso  = false;
                    retorno.Mensagem = "Não foi possível atualizar a aresta no arquivo!";
                    return(retorno);
                }
            }catch (Exception ex)
            {
                VariaveisGlobais.telaPrincipal.AtualizarLog(ex.Message);
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível atualizar a aresta! " + ex.Message;
                return(retorno);
            }
            finally
            {
                Monitor.Exit(VariaveisGlobais.lockerAresta);
            }

            VariaveisGlobais.telaPrincipal.AtualizarLog("Aresta " + a.Descricao + " atualizado com sucesso!");
            retorno.Mensagem = "Aresta atualizado com sucesso!";

            return(retorno);
        }
Exemple #19
0
        public override bool Equals(object obj)
        {
            Aresta a = (Aresta)obj;

            if (this.vertice1.Equals(a.vertice1) && this.vertice2.Equals(a.vertice2) && this.peso == a.peso)
            {
                return(true);
            }

            if (!this.ehDirecionada && this.vertice1.Equals(a.vertice2) && this.vertice2.Equals(a.vertice1) && this.peso == a.peso)
            {
                return(true);
            }

            return(false);
        }
Exemple #20
0
        private async void DeleteSingle(object sender, KeyRoutedEventArgs e)
        {
            var list = sender as ListBox;

            try
            {
                if (e.Key == Windows.System.VirtualKey.Delete)
                {
                    if (list.Name == "Vertex_list")
                    {
                        Vertice vertice_aux = Graph.BuscaVertice(list.SelectedItem.ToString());

                        Graph.RemoveVertice(vertice_aux);

                        v1_box.Items.Remove(vertice_aux.Label);
                        v2_box.Items.Remove(vertice_aux.Label);
                        if (Graph.Vertices.Count > 0)
                        {
                            Vertex_list.ItemsSource = Graph.VerticeToListString();
                        }
                        else
                        {
                            Vertex_list.ItemsSource = null;
                        }
                    }
                    else if (list.Name == "Aresta_list")
                    {
                        Aresta aresta_aux = Graph.Arestas[int.Parse(list.SelectedItem.ToString().Remove(list.SelectedItem.ToString().IndexOf(']')).Remove(list.SelectedItem.ToString().IndexOf('['), 1))];
                        Graph.RemoveAresta(aresta_aux);
                        if (Graph.Arestas.Count > 0)
                        {
                            Aresta_list.ItemsSource = Graph.ArestaToListString();
                        }
                        else
                        {
                            Aresta_list.ItemsSource = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msgdi = new MessageDialog($"Erro {ex.Message}");
                await msgdi.ShowAsync();
            }
        }
Exemple #21
0
        public static int[] CalculaDjkstra(int VerticeOrigem, Grafo Grafo)
        {
            Queue <int> filaVisita = new Queue <int>();

            if (Grafo == null || Grafo.NumeroVertices == 0)
            {
                throw new Exception("Grafo nao foi definido");
            }
            int[] retorno = new int[Grafo.NumeroVertices];
            int[] peso    = new int[Grafo.NumeroVertices];
            int[] visitas = new int[Grafo.NumeroVertices];
            for (int i = 0; i < retorno.Length; i++)
            {
                retorno[i] = i;
                peso[i]    = int.MaxValue;
                visitas[i] = 0;
            }

            filaVisita.Enqueue(VerticeOrigem);
            retorno[VerticeOrigem] = VerticeOrigem; // o Vertice de origem é a propria origem
            visitas[VerticeOrigem] = 1;
            peso[VerticeOrigem]    = 0;

            while (filaVisita.Count > 0)
            {
                Vertice    verticeAtual = Grafo.GetVertice(filaVisita.Dequeue());
                List <int> adjacentes   = verticeAtual.Adjacentes;
                foreach (var item in adjacentes)
                {
                    Aresta arestaAt = Grafo.ObtenhaAresta(verticeAtual.Id, item);
                    if (visitas[item] != 1)
                    {
                        filaVisita.Enqueue(item);
                    }
                    visitas[item] = 1;//visitado
                    if ((peso[verticeAtual.Id] + arestaAt.Peso) < peso[item])
                    {
                        peso[item]    = peso[verticeAtual.Id] + arestaAt.Peso;
                        retorno[item] = verticeAtual.Id;
                    }
                }
            }
            return(retorno);
        }
Exemple #22
0
        public Aresta[] Ordenar(Aresta[] vet)
        {
            int    tamanho = vet.Length;
            Aresta temp    = vet[0];

            for (int i = 0; i < tamanho; i++)
            {
                for (int j = i + 1; j < tamanho; j++)
                {
                    if (vet[i].Peso > vet[j].Peso)
                    {
                        temp   = vet[i];
                        vet[i] = vet[j];
                        vet[j] = temp;
                    }
                }
            }
            return(vet);
        }
Exemple #23
0
        /// <summary>
        /// Checks Rem-combobox and confirms the operation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Confirm_rem_item(object sender, RoutedEventArgs e)
        {
            try
            {
                if (selected_item_name == "Grafo")
                {
                    Graph       = null;
                    Graph_exist = false;
                    graphStats.SetGrafo(Graph);
                    v1_box.Items.Clear();
                    v2_box.Items.Clear();
                    GraphCreate.Visibility = Visibility.Visible;
                    Drawer.ClearCanvas();
                }
                else if (selected_item_name == "Vértice")
                {
                    Vertice vertice_aux = Graph.BuscaVertice(lbl_rem_box.Text);

                    Graph.RemoveVertice(vertice_aux);

                    v1_box.Items.Remove(vertice_aux.Label);
                    v2_box.Items.Remove(vertice_aux.Label);
                }
                else if (selected_item_name == "Aresta")
                {
                    Aresta aresta_aux = Graph.BuscaAresta($"{Graph.BuscaVertice(v1_rem_box.SelectedItem.ToString())._id} {Graph.BuscaVertice(v2_rem_box.SelectedItem.ToString())._id}");
                    Graph.RemoveAresta(aresta_aux);
                }
            }
            catch (Exception ex)
            {
                msgdi = new MessageDialog($"Erro {ex.Message}");
                await msgdi.ShowAsync();
            }

            if (selected_item_name != "")
            {
                myConsole.AddStringToConsole($"\n{selected_item_name} foi removido.");
            }

            myConsole.Update();
            graphStats.Update();
        }
Exemple #24
0
        public FormGrafo(Grafo grafo)
        {
            InitializeComponent();
            Grafo = grafo;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

            No[] ItemObject = new No[grafo.Nos.Count];
            for (int i = 0; i < grafo.Nos.Count; i++)
            {
                ItemObject[i] = grafo.Nos[i];
            }
            Aresta[] ItemObject1 = new Aresta[grafo.Arestas.Count];
            for (int i = 0; i < grafo.Arestas.Count; i++)
            {
                ItemObject1[i] = grafo.Arestas[i];
            }
            comboBox1.Items.AddRange(ItemObject);
            comboBox2.Items.AddRange(ItemObject);
            dataGridView1.DataSource = Grafo.Nos;
            dataGridView2.DataSource = Grafo.Arestas;
        }
        public void PintarArestasDeIdaEVolta()
        {
            var arestasDaOrigem = Arestas.Where(a => a.Antecessor.Identificador == "Sede").ToList();
            var corLaranja      = Cores.First(c => c.Nome == "Laranja");

            foreach (var aresta in arestasDaOrigem)
            {
                aresta.Cor = corLaranja.Hexadecimal;

                var arestaNova = new Aresta()
                {
                    Codigo     = Arestas.Last().Codigo + 1,
                    Custo      = aresta.Custo,
                    Antecessor = aresta.Sucessor,
                    Sucessor   = aresta.Antecessor,
                    Cor        = corLaranja.Hexadecimal
                };

                Arestas.Add(arestaNova);
            }
        }
Exemple #26
0
        public IHttpActionResult AdicionarAresta([FromBody] dynamic jsonPostData)
        {
            try
            {
                Aresta aresta = JsonConvert.DeserializeObject <Aresta>(jsonPostData.aresta.ToString()) as Aresta;

                No origem = new No();
                origem.Id = aresta.Origem;

                No destino = new No();
                destino.Id = aresta.Destino;

                Aresta arestaAdd = _Grafo.CriarAresta(origem, destino);

                return(Ok(arestaAdd));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #27
0
        public Retorno insertAresta(Aresta a)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            atualizarGrafo();

            Vertice v1 = null;
            Vertice v2 = null;

            v1 = this.Vertices.Where(p => p.Nome == a.VerticeInicio).FirstOrDefault();
            v2 = this.Vertices.Where(p => p.Nome == a.VerticeFim).FirstOrDefault();

            if (v1 == null || v2 == null)
            {
                //Implica que algum vértice informado não existe
                Console.WriteLine("Algum dos vértices informados não existe!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Algum dos vértices informados não existe!";
                return(retorno);
            }

            this.Arestas.Add(a);

            if (!Util.escreverGrafoArquivo(this, Util.caminho))
            {
                Console.WriteLine("Não foi possível gravar a aresta no arquivo!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível gravar a aresta no arquivo!";
                return(retorno);
            }

            Monitor.Exit(locker);

            Console.WriteLine("Aresta cadastrado com sucesso!");
            retorno.Mensagem = "Aresta cadastrado com sucesso!";

            return(retorno);
        }
Exemple #28
0
        public IHttpActionResult RemoverAresta([FromBody] dynamic jsonPostData)
        {
            try
            {
                Aresta a = JsonConvert.DeserializeObject <Aresta>(jsonPostData.aresta.ToString()) as Aresta;

                Aresta arestaRemover = _Grafo.RemoverAresta(a);

                if (arestaRemover != null)
                {
                    return(Ok(arestaRemover));
                }
                else
                {
                    return(BadRequest("Aresta não encontrada!"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public void AdicionarAresta()
        {
            MensagemDeErro = string.Empty;

            if (Arestas.Any(a => (a.Antecessor.Identificador == Antecessor && a.Sucessor.Identificador == Sucessor) ||
                            (a.Sucessor.Identificador == Antecessor && a.Antecessor.Identificador == Sucessor)))
            {
                MensagemDeErro = "Os vertices selecionados já estão ligados entre si.";
                return;
            }
            else if (Antecessor == Sucessor)
            {
                MensagemDeErro = "Não é possível fazer essa ligação.";
                return;
            }

            Aresta.Antecessor = Vertices.First(v => v.Identificador == Antecessor);
            Aresta.Sucessor   = Vertices.First(v => v.Identificador == Sucessor);
            Aresta.Codigo     = Arestas.Any() ? Arestas.Last().Codigo++ : 0;
            Arestas.Add(Aresta);

            Aresta = new Aresta();
        }
Exemple #30
0
        private void btnBuscarVerticesAresta_Click(object sender, RoutedEventArgs e)
        {
            if (txtDescricaoArestaListar.Text == "")
            {
                MessageBox.Show("Por favor informe a descrição da aresta a ser utilizada!");
                return;
            }

            Retorno r = client.getGrafo();

            GrafoAtributo grafo = JsonConvert.DeserializeObject <GrafoAtributo>(r.Retorno_);

            Aresta a = null;

            a = grafo.Arestas.Where(p => p.Descricao == txtDescricaoArestaListar.Text).FirstOrDefault();

            if (a == null)
            {
                txtDescricaoArestaListar.Text = "";
                MessageBox.Show("A aresta informada não existe!");
                return;
            }

            Retorno r1 = client.listarVerticesAresta(a);

            List <Vertice> vertices = JsonConvert.DeserializeObject <List <Vertice> >(r1.Retorno_);

            txtNomeVertice_V1.Text      = vertices[0].Nome.ToString();
            txtCorVertice_V1.Text       = vertices[0].Cor.ToString();
            txtDescricaoVertice_V1.Text = vertices[0].Descricao;
            txtPesoVertice_V1.Text      = vertices[0].Peso.ToString();

            txtNomeVertice_V2.Text      = vertices[1].Nome.ToString();
            txtCorVertice_V2.Text       = vertices[1].Cor.ToString();
            txtDescricaoVertice_V2.Text = vertices[1].Descricao;
            txtPesoVertice_V2.Text      = vertices[1].Peso.ToString();
        }