-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoardParser.java
More file actions
57 lines (48 loc) · 1.92 KB
/
Copy pathBoardParser.java
File metadata and controls
57 lines (48 loc) · 1.92 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
/*
* Reads in boards from file (intended to be boards.txt)
* if using other file, maintain same structure as boards.txt!
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BoardParser {
public static ArrayList<int[][]> parseBoardsFromFile(String filename) {
ArrayList<int[][]> boards = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
int[][] board = new int[9][9];
int row = 0;
while ((line = br.readLine()) != null) {
// Trim extra spaces and handle empty lines (separators for new boards)
line = line.trim();
if (line.isEmpty()) {
// If we encounter an empty line, it means we've reached the end of a board
if (row == 9) {
boards.add(board);
}
board = new int[9][9]; // Reset for the next board
row = 0;
continue;
}
// Remove square brackets and split the line by commas
line = line.replaceAll("[\\[\\]]", "");
String[] numbers = line.split(",");
// Convert each number from String to int
for (int col = 0; col < numbers.length; col++) {
board[row][col] = Integer.parseInt(numbers[col].trim());
}
row++;
}
// After the loop, add the last board if it was read completely
if (row == 9) {
boards.add(board);
}
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
System.out.println("Error parsing number: " + e.getMessage());
}
return boards;
}
}