package cn.gyk.shuzu;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
public class SparseArray {
public static void main(String[] args) {
int[][] chessArr = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][3] = 2;
// 输出数据
System.out.println("原始数据:");
for (int[] arr : chessArr) {
for (int num : arr) {
System.out.printf("%d\t", num);
}
System.out.println();
}
// 找到原始数据中一共多少有效数据
int sum = 0;
for (int i = 0; i < chessArr.length; i++) {
for (int j = 0; j < chessArr[0].length; j++) {
if (chessArr[i][j] != 0) {
sum++;
}
}
}
// 算出稀疏数组的第一行
int[][] spaseArray = new int[sum + 1][3];
spaseArray[0][0] = chessArr.length;
spaseArray[0][1] = chessArr[0].length;
spaseArray[0][2] = sum;
// 遍历数组
int count = 0;
for (int i = 0; i < chessArr.length; i++) {
for (int j = 0; j < chessArr[0].length; j++) {
if (chessArr[i][j] != 0) {
count++;
spaseArray[count][0] = i;
spaseArray[count][1] = j;
spaseArray[count][2] = chessArr[i][j];
}
}
}
// 新数组
System.out.println("新数组:");
for (int i = 0; i < spaseArray.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", spaseArray[i][0], spaseArray[i][1], spaseArray[i][2]);
}
System.out.println();
// 将稀疏数组保存到磁盘
File file = new File("sparse.dat");
Writer writer = null;
try {
writer = new FileWriter(file);
for (int[] row : spaseArray) {
for (int i : row) {
writer.write(i);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从磁盘中读数据
File sparseFile = new File("sparse.dat");
Reader reader = null;
ArrayList<Integer> arrayList = new ArrayList<>();
try {
reader = new FileReader(sparseFile);
int data;
while ((data = reader.read()) != -1) {
arrayList.add(data);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 将文件转为稀疏数组
int row = arrayList.size();
int[][] sparseArr2 = new int[row / 3][3];
for (int i = 0; i < row; i++) {
sparseArr2[i / 3][i % 3] = arrayList.get(i);
}
// 磁盘恢复后的数组
System.out.println("磁盘恢复后的数组:");
for (int i = 0; i < sparseArr2.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr2[i][0], sparseArr2[i][1], sparseArr2[i][2]);
}
// 稀疏数组转化为普通数组
int[][] chessArr2 = new int[sparseArr2[0][0]][sparseArr2[0][1]];
for (int i = 1; i < sparseArr2.length; i++) {
chessArr2[sparseArr2[i][0]][sparseArr2[i][1]] = sparseArr2[i][2];
}
// 磁盘还原后的数组
System.out.println("磁盘还原后的数组:");
for (int[] arr : chessArr2) {
for (int num : arr) {
System.out.printf("%d\t", num);
}
System.out.println();
}
}
}