将 原始数组 转化为 稀疏数组保存到文件 代码如下
。
// 二维数组压缩为稀疏数组
@Test
public void test(){
//创建原始数组
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][4] = 2;
//显示遍历
System.out.println("原始的二维数组。。");
for(int[] row:chessArr1){
for (int i : row) {
System.out.printf("%d\t",i);
}
System.out.println();
}
//遍历数值个数
System.out.println("转化为稀疏数组。。");
int sum = 0 ;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArr1[i][j] != 0 ){
sum++;
}
}
}
//创建稀疏数组
int sparseArr[][] = new int[sum+1][3];
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter("read.txt");
bw = new BufferedWriter(fw);
bw.write(11+" ");
bw.write(11+" ");
bw.write(sum+" ");
bw.newLine();
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArr1[i][j] != 0 ){
bw.write(i+" ");
bw.write(j+" ");
bw.write(chessArr1[i][j]+" ");
bw.newLine();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
把 文件 稀疏数组转化为原始数组 代码如下
。
// 稀疏还原二维数组
@Test
public void test1() throws IOException{
FileReader fr=new FileReader("read.txt");
BufferedReader br= new BufferedReader(fr);
String str="";
//保存每行数据到list集合
List<String> list=new ArrayList<>();
while((str = br.readLine()) != null){
list.add(str);
}
str = (String)list.get(0);
String[] split = str.split(" ");
int chessArrL[][] =new int[Integer.parseInt(split[0])][Integer.parseInt(split[1])];
for (int i =1; i <Integer.parseInt(split[2])+1 ; i++) {
String str1 =(String)list.get(i);
String[] s = str1.split(" ");
chessArrL[Integer.parseInt(s[0])][Integer.parseInt(s[1])]=Integer.parseInt(s[2]);
}
for(int[] row:chessArrL) {
for(int data:row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
}