package com.h.sparsearray;
import java.io.*;
/**
* @Auther: Hao
* @Date:2021/6/5
*/
public class SparseArray {
public static void main(String[] args) {
//五子棋 存储
//第一步 创建一个原始二维数组 11*11
//0:表示没有棋子 1表示黑子 2表示白子
System.out.println("初始二维数组如下:");
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[2][9] = 1;
chessArr1[2][10] = 1;
chessArr1[6][7] = 2;
for (int[] row : chessArr1) {
for (int i : row) {
System.out.printf("%d\t", i);
}
System.out.println();
}
//第二步 将二维数组转化为稀疏数组
int sum = 0;
for (int[] row : chessArr1) {
for (int i : row) {
if (i != 0) {
sum++;
}
}
}
int sparseArray[][] = new int[sum + 1][3];
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//遍历二维数组 将非零数组存放进稀疏数组
int count = 0;//用于记录是第几个非0数据
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArray[count][2] = chessArr1[i][j];
sparseArray[count][1] = j;
sparseArray[count][0] = i;
}
}
}
//遍历输出稀疏数组
System.out.println();
System.out.println("二维数组转化得到稀疏数组为:");
for (int[] spa : sparseArray) {
for (int i : spa) {
System.out.printf("%d\t", i);
}
System.out.println();
}
//第三步 将稀疏数组数据存入磁盘
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(new File("C:\\路径\\DATA8.data"));
for (int i = 0; i < sparseArray.length; i++) {
if (i == sparseArray.length - 1) {
fileWriter.append(sparseArray[i][0] + "," + sparseArray[i][1] + "," + sparseArray[i][2]);
} else {
fileWriter.append(sparseArray[i][0] + "," + sparseArray[i][1] + "," + sparseArray[i][2] + ",");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//第四步 取出磁盘数据 恢复稀疏数组
FileReader fileReader = null;
StringBuffer strB = new StringBuffer();
try {
fileReader = new FileReader(new File("C:\\路径\\DATA8.data"));
while (fileReader.ready()) {
strB.append((char) fileReader.read());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] str = strB.toString().split(",");
int sparseArray2[][] = new int[str.length / 3][3];
for (int i = 0; i < sparseArray2.length; i++) {
for (int j = 0, p = i * 3; j < 3; j++, p++) {
sparseArray2[i][j] = Integer.parseInt(str[p]);
}
}
System.out.println();//输出从磁盘读取到的稀疏数组
System.out.println("从磁盘中读取的稀疏数组为:");
for (int[] ints : sparseArray2) {
for (int i : ints) {
System.out.printf("%d\t", i);
}
System.out.println();
}
//第五步 将稀疏数组恢复成二维数组
int chessArr2[][] = new int[sparseArray2[0][0]][sparseArray2[0][1]];
for (int i = 1; i < sum + 1; i++) {
chessArr2[sparseArray2[i][0]][sparseArray2[i][1]] = sparseArray2[i][2];
}
//遍历输出恢复之后的二维数组(解压缩)
System.out.println();
System.out.println("解压缩得到二维数组是:");
for (int[] cheArr : chessArr2) {
for (int i : cheArr) {
System.out.printf("%d\t", i);
}
System.out.printf("\n");
}
}
}