思路:
1. 以文件保存稀疏矩陣
2. 以稀疏矩陣保存棋子所在的X,Y座標、與值(1代表黑子、2代表白子)
3. 讀取文件還原稀疏矩陣
4. 將稀疏矩陣還原成原二維陣列
先上棋盤圖:
把棋盤圖轉為稀疏矩陣:
0 12 12 19
1 2 9 2
2 3 2 2
3 4 3 1
4 4 6 2
5 5 4 1
6 5 5 2
7 5 6 1
8 5 7 1
9 6 4 2
10 6 5 1
11 6 6 1
12 6 7 2
13 7 4 1
14 7 5 2
15 7 6 1
16 8 3 1
17 8 4 1
18 8 6 2
19 8 7 2
// 稀疏矩陣(黑子:1 白子:2) 12*12 共19子
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
// 文件取出來的資料放入稀疏矩陣
String filePath = "C:/Users/ching/Documents/chessSparseArray.txt";
int[][] chessSparseArray = readFilesToSparseArray(filePath);
int[][] array = new int[chessSparseArray[0][0]][chessSparseArray[0][1]];
// 把稀疏矩陣之值指定到二維陣列(從稀疏矩陣第二列開始讀)
for (int i = 1; i < chessSparseArray.length; i++) {
array[chessSparseArray[i][0]][chessSparseArray[i][1]] = chessSparseArray[i][2];
}
// 印出二維陣列(原始五子棋盤)
for (int[] row: array) {
for (int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
public static int[][] readFilesToSparseArray(String filePath) {
try {
List<String> readAllLines = Files.readAllLines(Paths.get(filePath));
int num = readAllLines.size();
// num-1扣除最後一行註釋
int[][] chessSparseArray = new int[num-1][3];
Supplier<Stream<String>> streamSupplier = () -> readAllLines
.stream();
streamSupplier.get().forEach(line ->
{
if (line.startsWith("//")) {
return;
}
String blank = " ";
String index1Val = ""; // X座標
String index2Val = ""; // Y座標
String index3Val = ""; // 黑子或白子
int currentLine = Integer.valueOf(line.substring(0,2).trim());
if (!blank.equals(line.substring(2,3))) {
index1Val = line.substring(2,4);
} else {
index1Val = line.substring(3,4);
}
if (!blank.equals(line.substring(5,6))) {
index2Val = line.substring(5,7);
} else {
index2Val = line.substring(6,7);
}
if (!blank.equals(line.substring(8,9))) {
index3Val = line.substring(8,10);
} else {
index3Val = line.substring(9,10);
}
chessSparseArray[currentLine][0] = Integer.valueOf(index1Val);
chessSparseArray[currentLine][1] = Integer.valueOf(index2Val);
chessSparseArray[currentLine][2] = Integer.valueOf(index3Val);
});
return chessSparseArray;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!