/// <summary>
        /// Faz a multiplicação de duas matrizes esparsas.
        /// </summary>
        /// <param name="outraMatriz"></param>
        /// <returns>Uma matriz esparsa representando a multiplicação.</returns>
        public ListaLigadaCruzada MultiplicarMatrizes(ListaLigadaCruzada outraMatriz)
        {
            if (this.Colunas != outraMatriz.Linhas)
            {
                throw new ArgumentException("Número de colunas de uma matriz deve ser igual o número de linhas da outra");
            }

            ListaLigadaCruzada matrizResultado;

            matrizResultado = new ListaLigadaCruzada(this.Linhas, outraMatriz.Colunas);


            double total = 0;

            for (int i = 0; i < this.Linhas; i++)
            {
                for (int j = 0; j < outraMatriz.Colunas; j++)
                {
                    total = 0;
                    int k;
                    for (k = 0; k < this.Colunas; k++)
                    {
                        total += this.ValorDe(i, k) * outraMatriz.ValorDe(k, j);
                    }
                    if (total != 0)
                    {
                        matrizResultado.InserirElemento(total, i, j);
                    }
                }
            }

            return(matrizResultado);
        }
예제 #2
0
        public void LerArquivo()
        {
            if (dlgAbrir.ShowDialog() == DialogResult.OK)
            {
                StreamReader       arquivo = new StreamReader(dlgAbrir.FileName);
                int                linhas  = int.Parse(arquivo.ReadLine());           //Lê-se as quantidade de linhas e colunas do arquivo
                int                colunas = int.Parse(arquivo.ReadLine());
                ListaLigadaCruzada li      = new ListaLigadaCruzada(linhas, colunas); //Cria-se uma nova para não ser necessário
                                                                                      //escrever o código duas vezes

                while (!arquivo.EndOfStream)
                {
                    string texto = arquivo.ReadLine();

                    int    linha = int.Parse(texto.Substring(1, 2));//Busca de dentro da string os valores necessários para a inclusão
                    int    col   = int.Parse(texto.Substring(4, 2));
                    double valor = double.Parse(texto.Substring(7, 5));

                    li.InserirElemento(valor, linha, col);
                }

                if (rbLista1.Checked) //Caso foi solicitado pelo usuário que esse arquivo seja a lista1, exibi-la no primeiro DGV
                {
                    lista = li;
                    lista.ExibirDataGridview(dgvUm);
                }
                else //Caso não, exibi-lo no segundo
                {
                    lista2 = li;
                    lista2.ExibirDataGridview(dgvDois);
                }
            }
        }
        /// <summary>
        /// Faz a soma de duas matrizes esparsas.
        /// </summary>
        /// <param name="outraMatriz"></param>
        /// <returns>Uma matriz esparsa representando a soma.</returns>
        public ListaLigadaCruzada SomarMatrizes(ListaLigadaCruzada outraMatriz)
        {
            if (this.linhas != outraMatriz.linhas || this.colunas != outraMatriz.colunas)
            {
                throw new ArgumentException("As Matrizes dever ser de mesma dimensão!");
            }

            ListaLigadaCruzada soma = new ListaLigadaCruzada(this.linhas, this.colunas);

            Celula atual = this.cabecaPrincipal.Abaixo.Direita;

            // Copia a matriz this na matriz soma
            for (int l = 0; l < this.linhas; l++)
            {
                for (int c = atual.Coluna; c >= 0; c = atual.Coluna)
                {
                    if (atual.Valor != null)
                    {
                        atual = atual.Direita;
                        soma.InserirElemento(this.ValorDe(l, c), l, c);
                    }
                }
                atual = atual.Abaixo.Direita;
            }

            atual = outraMatriz.cabecaPrincipal.Abaixo.Direita;

            for (int l = 0; l < outraMatriz.linhas; l++)
            {
                for (int c = atual.Coluna; c >= 0; c = atual.Coluna)
                {
                    if (atual.Valor != null)
                    {
                        double elem = soma.ValorDe(l, c) != 0 ? soma.ValorDe(l, c) + outraMatriz.ValorDe(l, c)
                                                                : outraMatriz.ValorDe(l, c);

                        soma.InserirElemento(elem, l, c);
                        atual = atual.Direita;
                    }
                }
                atual = atual.Abaixo.Direita;
            }

            return(soma);
        }
        /// <summary>
        /// Lê um arquivo contendo os dados da matriz esparsa (coordenadas e células diferente de 0).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLerArquivo_Click(object sender, EventArgs e)
        {
            MessageBox.Show("O arquivo deve conter as coordenadas que a matriz terá e depois" +
                            " as células diferentes de 0 (elemento, linha, coluna). Exemplo: \n" +
                            " 3 3 \n 10 0 0 \n 15 0 2", "Orientações de arquivo de matriz esparsa:",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(openFileDialog1.FileName);

                string linhaArquivo = sr.ReadLine();

                while (linhaArquivo.Contains("//")) // usado para pular comentários no arquivo
                {
                    linhaArquivo = sr.ReadLine();
                }

                string[] coordenadas = linhaArquivo.Split(' ');

                int linhas  = Convert.ToInt32(coordenadas[0]);
                int colunas = Convert.ToInt32(coordenadas[1]);

                matrizEsparsa = new ListaLigadaCruzada(linhas, colunas);

                while ((linhaArquivo = sr.ReadLine()) != null)
                {
                    if (linhaArquivo.Contains("//")) // pular comentários durante a inserção de células
                    {
                        continue;
                    }

                    string[] celula = linhaArquivo.Split(' ');

                    double elemento = Convert.ToDouble(celula[0]);
                    int    linha    = Convert.ToInt32(celula[1]);
                    int    coluna   = Convert.ToInt32(celula[2]);

                    matrizEsparsa.InserirElemento(elemento, linha, coluna);
                }
                sr.Close();

                // atualiza os campos necessários
                numLinhas.Value  = matrizEsparsa.Linhas;
                numColunas.Value = matrizEsparsa.Colunas;

                numLinhaPesquisa.Maximum  = numLinhaInsercao.Maximum = matrizEsparsa.Linhas - 1;
                numColunaPesquisa.Maximum = numColunaInsercao.Maximum = matrizEsparsa.Colunas - 1;

                matrizEsparsa.ExibirDataGridView(dgMatrizEsparsa);
            }
        }
        /// <summary>
        /// Insere o elemento na matriz esparsa indicada pelo programa.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInserirElemento_Click(object sender, EventArgs e)
        {
            double elemento;

            if (double.TryParse(txtElementoInsercao.Text, out elemento) && elemento != 0 &&
                numLinhaInsercao.Value >= 0 && numColunaInsercao.Value >= 0 && !matrizEsparsa.EstaDesalocada)
            {
                int linha  = Convert.ToInt32(numLinhaInsercao.Value);
                int coluna = Convert.ToInt32(numColunaInsercao.Value);

                matrizEsparsa.InserirElemento(elemento, linha, coluna);
                matrizEsparsa.ExibirDataGridView(dgMatrizEsparsa);
            }
            else
            {
                MessageBox.Show("Não é possível inserir um elemento na matriz! " +
                                " Verifique se os valores dos campos de inserção são válidos ou se há uma matriz.",
                                "Atenção!",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #6
0
        private void BtnInserir_Click(object sender, EventArgs e)
        {
            if (rbLista1.Checked)
            {
                if (lista == null)
                {
                    throw new Exception("Matriz Vazia");//Nesse caso não é possível realizar com uma lista padrão,
                }
                //então o código deve ser feito duas vezes

                //Chama-se os métodos já implementados na ListaLigadaCruzada
                lista.InserirElemento(double.Parse(txtValor.Text), Convert.ToInt32(numLinha.Value), Convert.ToInt32(numColuna.Value));
                lista.ExibirDataGridview(dgvUm);
            }
            else
            {
                if (lista2 == null)
                {
                    throw new Exception("Matriz Vazia");
                }
                lista2.InserirElemento(double.Parse(txtValor.Text), Convert.ToInt32(numLinha.Value), Convert.ToInt32(numColuna.Value));
                lista2.ExibirDataGridview(dgvDois);
            }
        }
예제 #7
0
        private void LerMatriz(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(openFileDialog1.FileName);

                string linhaArquivo = sr.ReadLine();

                while (linhaArquivo.Contains("//")) // usado para pular comentários no arquivo
                {
                    linhaArquivo = sr.ReadLine();
                }

                string[] coordenadas = linhaArquivo.Split(' ');

                int linhas  = Convert.ToInt32(coordenadas[0]);
                int colunas = Convert.ToInt32(coordenadas[1]);

                switch (Convert.ToInt32(((Button)sender).Tag))
                {
                case 0:
                {
                    matrizEsparsa1 = new ListaLigadaCruzada(linhas, colunas);
                    break;
                }

                case 1:
                {
                    matrizEsparsa2 = new ListaLigadaCruzada(linhas, colunas);
                    break;
                }
                }

                while ((linhaArquivo = sr.ReadLine()) != null)
                {
                    if (linhaArquivo.Contains("//")) // pular comentários durante a inserção de células
                    {
                        continue;
                    }

                    string[] celula = linhaArquivo.Split(' ');

                    double elemento = Convert.ToDouble(celula[0]);
                    int    linha    = Convert.ToInt32(celula[1]);
                    int    coluna   = Convert.ToInt32(celula[2]);

                    switch (Convert.ToInt32(((Button)sender).Tag))
                    {
                    case 0:
                    {
                        matrizEsparsa1.InserirElemento(elemento, linha, coluna);

                        // Atualiza os campos necessários
                        numLinhaInsercaoMatriz1.Maximum  = matrizEsparsa1.Linhas - 1;
                        numColunaInsercaoMatriz1.Maximum = matrizEsparsa1.Colunas - 1;

                        numLinhasMatriz1.Value  = matrizEsparsa1.Linhas;
                        numColunasMatriz1.Value = matrizEsparsa1.Colunas;

                        matrizEsparsa1.ExibirDataGridView(dgMatrizEsparsa1);
                        break;
                    }

                    case 1:
                    {
                        matrizEsparsa2.InserirElemento(elemento, linha, coluna);

                        // Atualiza os campos necessários
                        numLinhaInsercaoMatriz2.Maximum  = matrizEsparsa2.Linhas - 1;
                        numColunaInsercaoMatriz2.Maximum = matrizEsparsa2.Colunas - 1;

                        numLinhasMatriz2.Value  = matrizEsparsa2.Linhas;
                        numColunasMatriz2.Value = matrizEsparsa2.Colunas;

                        matrizEsparsa2.ExibirDataGridView(dgMatrizEsparsa2);
                        break;
                    }
                    }
                }
                sr.Close();
            }
        }
예제 #8
0
        private void InserirElemento(object sender, EventArgs e)
        {
            double elemento;

            switch (Convert.ToInt32(((Button)sender).Tag))
            {
            case 0:
            {
                if (double.TryParse(txtNumero.Text, out elemento) && elemento != 0 &&
                    numLinhaInsercaoMatriz1.Value >= 0 && numColunaInsercaoMatriz1.Value >= 0 && !matrizEsparsa1.EstaDesalocada)
                {
                    int linha  = Convert.ToInt32(numLinhaInsercaoMatriz1.Value);
                    int coluna = Convert.ToInt32(numColunaInsercaoMatriz1.Value);

                    matrizEsparsa1.InserirElemento(elemento, linha, coluna);
                    matrizEsparsa1.ExibirDataGridView(dgMatrizEsparsa1);
                }
                else
                {
                    MessageBox.Show("Não é possível inserir um elemento na matriz! " +
                                    " Verifique se os valores dos campos de inserção são válidos ou se há uma matriz.",
                                    "Atenção!",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            }

            case 1:
            {
                if (double.TryParse(txtNumero2.Text, out elemento) && elemento != 0 &&
                    numLinhaInsercaoMatriz2.Value >= 0 && numColunaInsercaoMatriz2.Value >= 0 && !matrizEsparsa2.EstaDesalocada)
                {
                    int linha  = Convert.ToInt32(numLinhaInsercaoMatriz2.Value);
                    int coluna = Convert.ToInt32(numColunaInsercaoMatriz2.Value);

                    matrizEsparsa2.InserirElemento(elemento, linha, coluna);
                    matrizEsparsa2.ExibirDataGridView(dgMatrizEsparsa2);
                }
                else
                {
                    MessageBox.Show("Não é possível inserir um elemento na matriz! " +
                                    " Verifique se os valores dos campos de inserção são válidos ou se há uma matriz.",
                                    "Atenção!",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            }

            case 2:
            {
                if (double.TryParse(txtNumeroResultado.Text, out elemento) && elemento != 0 &&
                    numLinhaInsercaoMatriz3.Value >= 0 && numColunaInsercaoMatriz3.Value >= 0 && !matrizEsparsa3.EstaDesalocada)
                {
                    int linha  = Convert.ToInt32(numLinhaInsercaoMatriz3.Value);
                    int coluna = Convert.ToInt32(numColunaInsercaoMatriz3.Value);

                    matrizEsparsa3.InserirElemento(elemento, linha, coluna);
                    matrizEsparsa3.ExibirDataGridView(dgMatrizEsparsa3);
                }
                else
                {
                    MessageBox.Show("Não é possível inserir um elemento na matriz! " +
                                    " Verifique se os valores dos campos de inserção são válidos ou se há uma matriz.",
                                    "Atenção!",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            }
            }
        }