Warshall algoritimo [RESOLVIDO]

5 respostas
juninhoall
Boa noite, estou com uma dificuldade referente a leitura de dados de um arquivo txt, como posso implementar para que o arquivo caia no meu algorítimo ? Segue meu algoritimo, mas o resultado está se divergindo do que realmente era pra ser
package warshall;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author Luiz Almeida Júnior
 */
public class Warshall {

    static void fechamento(boolean ma[][], boolean mf[][]) {
        int i, j, k;

        // inicialização da matriz de fechamento
        for (i = 0; i < ma.length; i++) {
            for (j = 0; j < ma.length; j++) {
                mf[i][j] = ma[i][j];
            }
        }

        // algoritmo de Warshall
        for (k = 0; k < ma.length; k++) {
            for (i = 0; i < ma.length; i++) {
                if (mf[i][k]) {
                    for (j = 0; j < ma.length; j++) {
                        mf[i][j] = mf[i][j] || mf[k][j];
                    }
                }
            }
        }
    }

    static void imprime(boolean m[][]) {
        int i, j;
        for (i = 0; i < m.length; i++) {
            for (j = 0; j < m.length; j++) {
                System.out.print(m[i][j] + "\t");
            }
            System.out.println("");
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        boolean ma[][] = new boolean[3][3];
        boolean mf[][] = new boolean[3][3];

        try {
            InputStream entrada = new FileInputStream("C:\\Users\\Luiz Almeida Júnior\\Desktop\\Mat.txt");
            InputStreamReader reader = new InputStreamReader(entrada);
            BufferedReader buffer = new BufferedReader(reader);
            String texto;
            while ((texto = buffer.readLine()) != null) {
                System.out.println(texto);
            }
        } catch (FileNotFoundException e) {
            e.getMessage();
        }
        imprime(ma);
        fechamento(ma, mf);
        imprime(mf);
    }
}

ma[0][0] = false;
ma[1][0] = true;
ma[2][0] = true;
ma[0][1] = true;
ma[1][1] = false;
ma[2][1] = true;
ma[0][2] = true;
ma[1][2] = true;
ma[2][2] = false;

Esses são os dados que coloquei no txt.
Grato desde já.

5 Respostas

TerraSkilll

O que você quer é pegar os valores do arquivo texto e colocar na variável ma[][], é isso?

Faltou basicamente você pegar os valores, fazer as devidas comparações e atribuições, se entendi o que você precisa. Algo mais ou menos assim:

public static void main(String[] args) throws IOException {  
        boolean ma[][] = new boolean[3][3];  
        boolean mf[][] = new boolean[3][3];
        int i=0, j=0;
  
        try {  
            InputStream entrada = new FileInputStream("C:\\Users\\Luiz Almeida Júnior\\Desktop\\Mat.txt");  
            InputStreamReader reader = new InputStreamReader(entrada);  
            BufferedReader buffer = new BufferedReader(reader);  
            String texto;  
            while ((texto = buffer.readLine()) != null) {  
                System.out.println(texto);

               // pegando os valores
                ma[i][j] = (texto.contains("true"));

                i++;

                if (i==3) {
                  j++;
                  i = 0;
                }

            }  
        } catch (FileNotFoundException e) {  
            e.getMessage();  
        }  
        imprime(ma);  
        fechamento(ma, mf);  
        imprime(mf);  
    }

É claro, é um jeito meio "bruto" de fazer a coisa. Não é muito flexível (não permite, por exemplo, uma matriz diferente de 3x3). Mas deve clarear sua ideia quanto a esse aspecto. Qualquer coisa, pergunte ou explique melhor o que deseja.

Abraço.

juninhoall
TerraSkilll:
O que você quer é pegar os valores do arquivo texto e colocar na variável ma[][], é isso?

Faltou basicamente você pegar os valores, fazer as devidas comparações e atribuições, se entendi o que você precisa. Algo mais ou menos assim:

public static void main(String[] args) throws IOException {  
        boolean ma[][] = new boolean[3][3];  
        boolean mf[][] = new boolean[3][3];
        int i=0, j=0;
  
        try {  
            InputStream entrada = new FileInputStream("C:\\Users\\Luiz Almeida Júnior\\Desktop\\Mat.txt");  
            InputStreamReader reader = new InputStreamReader(entrada);  
            BufferedReader buffer = new BufferedReader(reader);  
            String texto;  
            while ((texto = buffer.readLine()) != null) {  
                System.out.println(texto);

               // pegando os valores
                ma[i][j] = (texto.contains("true"));

                i++;

                if (i==3) {
                  j++;
                  i = 0;
                }

            }  
        } catch (FileNotFoundException e) {  
            e.getMessage();  
        }  
        imprime(ma);  
        fechamento(ma, mf);  
        imprime(mf);  
    }

É claro, é um jeito meio "bruto" de fazer a coisa. Não é muito flexível (não permite, por exemplo, uma matriz diferente de 3x3). Mas deve clarear sua ideia quanto a esse aspecto. Qualquer coisa, pergunte ou explique melhor o que deseja.

Abraço.


Bah, muito obrigado pela ajuda, clareou sim. Muito obrigado mesmo,

juninhoall
TerraSkilll:
Outra forma de implementação seria,
package OutraForma;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author Luiz Almeida Júnior
 */
public class OutraForma {

    static void fechamento(boolean ma[][], boolean mf[][]) {
        int i, j, k;

        // inicialização da matriz de fechamento
        for (i = 0; i < ma.length; i++) {
            for (j = 0; j < ma.length; j++) {
                mf[i][j] = ma[i][j];
            }
        }

        // algoritmo de Warshall
        for (k = 0; k < ma.length; k++) {
            for (i = 0; i < ma.length; i++) {
                if (mf[i][k]) {
                    for (j = 0; j < ma.length; j++) {
                        mf[i][j] = mf[i][j] || mf[k][j];
                    }
                }
            }
        }
    }

    static void imprime(boolean m[][]) {
        int i, j;
        for (i = 0; i < m.length; i++) {
            for (j = 0; j < m.length; j++) {
                System.out.print(m[i][j] + "\t");
            }
            System.out.println("");
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {

        boolean ma[][] = new boolean[5][5];
        boolean mf[][] = new boolean[5][5];

        try {
            int i, j = 0;
            InputStream entrada = new FileInputStream("mat.txt");
            InputStreamReader reader = new InputStreamReader(entrada);
            BufferedReader buffer = new BufferedReader(reader);
            String texto;

            while ((texto = buffer.readLine()) != null) {
                int t = texto.length();
                for (i = 0; i < t; i++) {
                    if ("1".equals(texto.substring(i, i + 1))) {
                        ma[j][i] = true;
                    } else {
                        ma[j][i] = false;
                    }
                }
                j++;
            }
        } catch (FileNotFoundException e) {
            e.getMessage();
        }
        imprime(ma);
        fechamento(ma, mf);
        imprime(mf);
    }
}
Meu professor me deu uma ajuda nesse hoje, e fez esse, graças a você consegui intender como faria, obrigado mesmo.
A

Exemplo, nosso arquivo .txt contém…

ma[0][0] = false;

ma[1][0] = true;

ma[2][0] = true;

ma[0][1] = true;

ma[1][1] = false;

ma[2][1] = true;

ma[0][2] = true;

ma[1][2] = true;

ma[2][2] = false;

public static void main(String[] args) throws IOException { boolean ma[][] = new boolean[3][3]; //boolean mf[][] = new boolean[3][3]; String dir = "C:\\mat.txt"; try{ BufferedReader buffer = new BufferedReader(new FileReader(new File(dir))); for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ while(buffer.ready()){ ma[i][j] = buffer.readLine().contains("true"); break; } } } } catch(FileNotFoundException e) {} imprime(ma); // <-- Teste da leitura do Arquivo //fechamento(ma, mf); //imprime(mf); }Saída do teste seria isso:
[size=14]
false true true
true false true
true true false
[/size]
Reveja seu código, faça um teste com o código acima…
até…

juninhoall

andy11x:
Exemplo, nosso arquivo .txt contém…

ma[0][0] = false;

ma[1][0] = true;

ma[2][0] = true;

ma[0][1] = true;

ma[1][1] = false;

ma[2][1] = true;

ma[0][2] = true;

ma[1][2] = true;

ma[2][2] = false;

public static void main(String[] args) throws IOException { boolean ma[][] = new boolean[3][3]; //boolean mf[][] = new boolean[3][3]; String dir = "C:\\mat.txt"; try{ BufferedReader buffer = new BufferedReader(new FileReader(new File(dir))); for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ while(buffer.ready()){ ma[i][j] = buffer.readLine().contains("true"); break; } } } } catch(FileNotFoundException e) {} imprime(ma); // <-- Teste da leitura do Arquivo //fechamento(ma, mf); //imprime(mf); }Saída do teste seria isso:
[size=14]
false true true
true false true
true true false
[/size]
Reveja seu código, faça um teste com o código acima…
até…


Correto, só que usei no segundo uma matriz 5x5

Criado 3 de junho de 2014
Ultima resposta 4 de jun. de 2014
Respostas 5
Participantes 3