稀疏数组
作者:互联网
普通二维数组压缩成稀疏数组保存成文件,再从文件中读取稀疏数组,将其解析成普通二维数组
package sparse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class SpareArray {
public static void main(String[] args) throws IOException {
//创建一个原始的二维数组
//0表示没有棋子,1表示黑子,2表示白子
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][4] = 1;
PrintUtil.printMethod(chessArr1);
//转为稀疏数组
//1.统计有效数据的个数
int sum = 0;
for (int i = 0;i < chessArr1.length;i++){
for (int j = 0;j < chessArr1[i].length; j++){
if (chessArr1[i][j] != 0){
sum++;
}
}
}
//2.创建稀疏数组并初始化第一行
int sparseArr[][] = new int[sum+1][3];
sparseArr[0] = new int[]{11, 11, sum};
//3.赋值其他行
int count = 0;
for (int i = 0;i < chessArr1.length;i++){
for (int j = 0;j < chessArr1[i].length; j++){
if (chessArr1[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
//输出并存到文件中
File file = new File("D:/result/array/test01.txt");
FileWriter fw = new FileWriter(file);
for (int[] row : sparseArr){
for (int data : row){
System.out.print(data + "\t");
fw.write(data + "\t");
}
System.out.println();
fw.write("\n");
}
fw.close();
//从文件中读取稀疏数组
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<Integer> list = new ArrayList();
int row = 0,column = 0;
while ((line= br.readLine()) != null){
String[] temp = line.split("\t");
for (int i=0; i<temp.length; i++){
list.add(Integer.valueOf(temp[i]));
}
column = temp.length;
row++;
}
br.close();
int[][] sparseArr2 = new int[row][column];
int count2 = 0;
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
sparseArr2[i][j] = list.get(count2);
count2++;
}
}
//转为二维数组
int row2 = sparseArr2[0][0];
int column2 = sparseArr2[0][1];
int[][] chessArr2 = new int[row2][column2];
for (int i=1; i<sparseArr2[0][2] + 1; i++){
row2 = sparseArr2[i][0];
column2 = sparseArr2[i][1];
chessArr2[row2][column2] = sparseArr2[i][2];
}
PrintUtil.printMethod(chessArr2);
}
}
package sparse;
public class PrintUtil {
public static void printMethod(int[][] srcArray){
for(int[] rowCount : srcArray){//遍历二维数组的每一行
for (int data : rowCount){
System.out.print(data + "\t");
}
System.out.println();
}
}
}
标签:int,chessArr1,稀疏,++,数组,sparseArr,new 来源: https://blog.csdn.net/weixin_42523683/article/details/111360580