数据结构——稀疏数组
数据结构——稀疏数组
棋局存档问题:如何将一局五子棋保存下来,并实现读档
- 利用稀疏数组进行数据保存,IO流写入/读取文件,实现读档。
简单代码实现:
/**
* @author 萝卜
* @date 2022/4/6
* @dec 稀疏数组
*/
public class SparseArray {
public static void main(String[] args) throws IOException {
//棋盘大小
int[][] arr = new int[11][11];
//棋子布局,1为黑,2为白。
arr[3][7] = 1;
arr[2][6] = 2;
arr[9][6] = 1;
arr[1][3] = 2;
arr[10][9] = 1;
int count = 0;
System.out.println("原数组为:");
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.printf("%d\t", anInt);
if (anInt != 0) {
count++;
}
}
System.out.println();
}
System.out.println();
//实际数组-->稀疏数组
int[][] arr2 = new int[count + 1][3];
arr2[0][0] = arr.length;
arr2[0][1] = arr[0].length;
arr2[0][2] = count;
count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
count++;
arr2[count][0] = i;
arr2[count][1] = j;
arr2[count][2] = arr[i][j];
}
}
}
System.out.println("稀疏数组为:");
for (int[] ints : arr2) {
for (int anInt : ints) {
System.out.printf("%d\t", anInt);
}
System.out.println();
}
System.out.println();
//稀疏数组-->文件
System.out.println("开始写出数据");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("data.txt"));
StringBuffer buff = new StringBuffer();
boolean flag = false;
for (int[] ints : arr2) {
for (int anInt : ints) {
if (flag) {
buff.append(",").append(anInt);
} else {
buff.append(anInt);
}
flag = true;
}
}
out.write(buff.toString());
out.flush();
out.close();
System.out.println("输出数据为-->" + buff);
System.out.println();
System.out.println("开始还原数据");
Scanner s = new Scanner(new FileInputStream("data.txt"));
s.useDelimiter(",");
//文件-->稀疏数组
int[][] arr3 = new int[0][];
while (s.hasNext()) {
if (flag) {
arr3 = new int[s.nextInt()][s.nextInt()];
s.nextInt();
} else {
arr3[s.nextInt()][s.nextInt()] = s.nextInt();
}
flag = false;
}
//稀疏数组-->原数组
for (int[] ints : arr2) {
if (flag) {
arr3[ints[0]][ints[1]] = ints[2];
}
flag = true;
}
System.out.println("稀疏数组还原为:");
for (int[] ints : arr3) {
for (int anInt : ints) {
System.out.printf("%d\t", anInt);
}
System.out.println();
}
}
}
运行结果如下:
原数组为:
0 0 0 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0
稀疏数组为:
11 11 5
1 3 2
2 6 2
3 7 1
9 6 1
10 9 1
开始写出数据
输出数据为-->11,11,5,1,3,2,2,6,2,3,7,1,9,6,1,10,9,1
开始还原数据
稀疏数组还原为:
0 0 0 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0