Eventually I would like to write create a minimum spanning tree using Prim's algorithm. However, I am have having trouble with reading data from a csv text file and converting those strings into integers. Here is the input text file contents:
A,B,C
∞,1,∞
∞,5,∞
I can get my program to save these values into a 2D String array just fine. Now what I want to do is create two seperate arrays to represent this data. The first holds A,B,C and will be a 1D array. The second will hold:
∞,1,∞
∞,5,∞
and will be a 2D array; however, and here is the caveat, I need to convert the string representations of 1 and 5 into integers and I need to convert the ∞ symbol into a large number, in this case 999999.
Here is my attempt at doing so:
public static void primsAlgorithm(String[][] array) { System.out.println(); System.out.println("Finding the minimum spanning tree for the following weighted graph: "); System.out.println(); String[] vertexArray = new String[array.length]; int[][] adjMatrix = new int[array.length - 1][array.length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { vertexArray[j] = array[0][j]; if (array[i + 1][j].equals("\u221E")) { adjMatrix[i][j] = 999999; //if inf symbol is seen replace with high value weight } else { adjMatrix[i][j] = Integer.parseInt(array[i + 1][j]); } System.out.print("\t" + array[i][j]); } System.out.println(); } System.out.println("Vertex array: "); System.out.println(Arrays.toString(vertexArray)); System.out.println("adjMatrix: "); for (int i = 0; i < adjMatrix.length; i++) { for (int j = 0; j < adjMatrix[i].length; j++) { System.out.print("\t" + adjMatrix[i][j]); } System.out.println(); } }
I have been messing with this trying different things for about an two hours now and I am lost. I don't know why it isn't doing what I want. Here is the log from an attempt at running the program:
run:
Please select the algorithm you wish to run: 1 for Prim's algorithm, 2 for Kruskal's algorithmor 3 for Floyd-Warshall’s algorithm
1
You chose Prim's algorithm.
Finding the minimum spanning tree for the following weighted graph:
A B C
∞ 1 ∞
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at graphalgorithms.GraphAlgorithms.primsAlgorithm(Gra phAlgorithms.java:104)
at graphalgorithms.GraphAlgorithms.main(GraphAlgorith ms.java:36)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
Obviously, this has something to do with the sizing of my arrays but what? Any ideas as to what I am doing wrong? A more simple solution maybe? #headaches