这是第一篇正式的文章,可能在markdown格式使用上还不够熟练
这是原始数组转换为稀疏数组的具体做法:
以五子棋棋盘为应用场景,在保存当前棋盘状态时,因为含有太多的0,而浪费了内存,这里面使用稀疏数组大大节省了空间
下面是具体的代码实现:
package Array;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
//目标:将二维数组转换为稀疏数组,然后使用io存储到文件中
public class sparseArray {
public static void main(String[] args) throws Exception {
//创建原始二维数组
int chessArr[][] = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][3] = 2;
System.out.println("输出当前原始数组:");
for (int[] rows : chessArr) {
for (int data : rows) {
System.out.printf("%d\t", data);
}
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++; } } } System.out.println("原始数组实际元素个数为:" + sum); System.out.println("转换后的稀疏数组为:"); int[][] sparseArr = new int[sum + 1][3]; sparseArr[0][0] = chessArr.length; sparseArr[0][1] = chessArr[0].length; sparseArr[0][2] = sum; //表示稀疏数组下标 int m = 1; for (int i = 0; i < chessArr.length; i++) { for (int j = 0; j < chessArr[0].length; j++) { if (chessArr[i][j] != 0) { sparseArr[m][0] = i; sparseArr[m][1] = j; sparseArr[m][2] = chessArr[i][j]; m++; } } } //输出稀疏数组 for (int[] rows : sparseArr) { for (int data : rows) { System.out.printf("%d\t", data); } System.out.println(); } //使用io将稀疏数组存入文件 File file = new File("G:/haha.txt"); FileWriter fw = new FileWriter(file); for (int[] rows : sparseArr) { for (int data : rows) { fw.write(data + "\t"); } fw.write("\r\n"); } fw.close(); System.out.println("写入文件成功!!!"); //从文件中进行恢复 BufferedReader br = new BufferedReader(new FileReader(file)); String line; int row = 0; //创建一个新的稀疏数组接受读取出来的数据 int[][] sparseArr2 = new int[3][3];//加入已经知道大小 while ((line = br.readLine()) != null) { String[] temp = line.split("\t"); for (int i = 0; i < temp.length; i++) { sparseArr2[row][i] = Integer.parseInt(temp[i]); } row++; } br.close(); System.out.println("打印读取出来的稀疏数组:"); for (int[] rows : sparseArr2) { for (int data : rows) { System.out.printf("%d\t", data); } System.out.println(); } System.out.println("恢复原始~~~"); //同样为了避免仍然输出上面的原始数组,这里新创建一个原始数组 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[] rows : chessArr2) { for (int data : rows) { System.out.printf("%d\t", data); } System.out.println(); } System.out.println("读取成功!!!"); }
}
`