0

So far I have developed a program that uses an adjacency matrix to build a graph using linked implementation.

I'm stuck on how I can read a text file containing an adjacency matrix, and using that data instead of manually inputting the adjacency matrix.

For example, a text file containing the following:

4
0 1 1 0
1 1 1 1 
1 0 0 0 
1 1 0 1
6
0 1 0 1 1 0
1 0 0 1 1 0
0 0 1 0 0 1
0 0 0 0 1 0
1 0 0 0 0 0
0 0 1 0 0 1
3
0 1 1 
1 0 1 
1 1 0
John Doe
  • 9
  • 3
  • Hello and welcome to Stack Overflow. Do you look something like this? https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java – Anoroah Oct 13 '18 at 23:40

1 Answers1

1

You can use this method to read matrix data from file. This method returns a 2d array of bytes containing zeroes and ones.

public static void main(String[] args) throws IOException {
    byte[][] matrix = getMatrixFromFile("matrix.txt");

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + ((j + 1) == matrix[i].length ? "" : " "));
        }
        System.out.println();
    }
}

public static byte[][] getMatrixFromFile(String filename) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(filename));
    int size = Byte.parseByte(lines.get(0));
    byte[][] matrix = new byte[size][size];
    for (int i = 1; i < lines.size(); i++) {
        String[] nums = lines.get(i).split(" ");
        for (int j = 0; j < nums.length; j++) {
            matrix[i - 1][j] = Byte.parseByte(nums[j]);
        }
    }

    return matrix;
}

Here I am assuming the file will contain data for one matrix, like following, but my code can easily be extended to read data for multiple matrices and return a list of 2d byte array.

4
0 1 1 0
1 1 1 1 
1 0 0 0 
1 1 0 1
Pushpesh Kumar Rajwanshi
  • 17,850
  • 2
  • 16
  • 35