add support for loading and printing out matrices from files
This commit is contained in:
parent
ca37003f32
commit
00fba12eb2
|
@ -59,9 +59,14 @@ public class Main {
|
|||
if (allow_networking) {
|
||||
System.err.println("[WARN] File is missing, downloading random matrix from the server");
|
||||
fetchResource("http://lab2.kpi.dev:16554/matrix.py", matrix_file_name);
|
||||
} else {
|
||||
System.err.println("[WARN] File is missing; networking is disabled, not recovering");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
int[][] matrix = loadMatrixFromFile(matrix_file);
|
||||
|
||||
}
|
||||
|
||||
private static void fetchResource(String remote_url, String output_filename) {
|
||||
|
@ -106,4 +111,45 @@ public class Main {
|
|||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static int[][] loadMatrixFromFile(File matrix_file) {
|
||||
try {
|
||||
Scanner matrix_file_reader = new Scanner(matrix_file);
|
||||
|
||||
ArrayList<String> raw_matrix_lines = new ArrayList<String>();
|
||||
while (matrix_file_reader.hasNextLine()) {
|
||||
raw_matrix_lines.add(matrix_file_reader.nextLine());
|
||||
}
|
||||
|
||||
ArrayList<String[]> baked_matrix_lines = new ArrayList<String[]>();
|
||||
|
||||
for (String s : raw_matrix_lines) {
|
||||
baked_matrix_lines.add(s.split(" "));
|
||||
}
|
||||
|
||||
int ref_length = baked_matrix_lines.get(0).length;
|
||||
int[][] baked_matrix = new int[baked_matrix_lines.size()][ref_length];
|
||||
|
||||
for (int i = 0; i < baked_matrix_lines.size(); i++) {
|
||||
//for (String[] sa : baked_matrix_lines) {
|
||||
if (baked_matrix_lines.get(i).length != ref_length) {
|
||||
System.err.println("[ERROR] Matrix lines have different length! Assuming the matrix was corrupted");
|
||||
System.exit(2);
|
||||
}
|
||||
|
||||
for (int j = 0; j < baked_matrix_lines.get(i).length; j++) {
|
||||
System.out.print(baked_matrix_lines.get(i)[j] + " ");
|
||||
baked_matrix[i][j] = Integer.parseInt(baked_matrix_lines.get(i)[j]);
|
||||
}
|
||||
|
||||
System.out.print("\n");
|
||||
}
|
||||
|
||||
return baked_matrix;
|
||||
} catch (Exception e) {
|
||||
System.err.println("[ERROR] Failed to read matrix from file " + matrix_file.getName());
|
||||
System.exit(1);
|
||||
return new int[1][1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue