-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstanceFile.java
More file actions
61 lines (49 loc) · 2.14 KB
/
Copy pathInstanceFile.java
File metadata and controls
61 lines (49 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cwp.instance;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public record InstanceFile(String fileName, String name, String type) {
public Instance loadInstance() throws IOException, FormatException {
String resourcePath = "/instances/" + fileName;
InputStream inputStream = InstanceFile.class.getResourceAsStream(resourcePath);
if (inputStream == null) {
throw new IOException("Resource not found in the classpath: " + resourcePath);
}
return loadInstance(name, inputStream);
}
private Instance loadInstance(String name, InputStream inputStream) throws IOException, FormatException {
try (var br = new BufferedReader(new InputStreamReader(inputStream))) {
String line = br.readLine();
if (line == null) {
throw new FormatException("The file is empty");
}
StringTokenizer header = new StringTokenizer(line);
header.nextToken();
int numVertices = Integer.parseInt(header.nextToken());
if (!header.hasMoreTokens()) {
throw new FormatException(
"The first line must contain the number of vertices (duplicated) and the number of edges");
}
int numEdges = Integer.parseInt(header.nextToken());
int[][] weights = new int[numVertices][numVertices];
line = br.readLine();
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
int i = Integer.parseInt(st.nextToken());
int j = Integer.parseInt(st.nextToken());
weights[i][j] = 1;
weights[j][i] = 1;
line = br.readLine();
}
return new Instance(name, numVertices, numEdges, weights);
} catch (NumberFormatException e) {
throw new FormatException("Invalid file format");
}
}
@Override
public String toString() {
return "Name: " + name + " FileName:" + fileName;
}
}