稀疏数组的用处
当一个数组中大部分元素为0,或者为同一个值时,可以使用稀疏数组来保存该数组。
游戏存盘(五子棋)减少空间占用地图
数组到稀疏数组的转换
遍历原始数组获取原始数组有效个数 sum根据原始数组有效个数创建稀疏数组 new int [sum+1][3]稀疏数组第一行记录原始数组的行长、列长、数据有效个数遍历原始二维数组,保存有效数据到稀疏数组(元素行下标,列下标,元素值)
代码如下:
public class SparseArray {
public static void main(String
[] args
) throws IOException
{
int [][] numberArr
= new int[11][11];
numberArr
[1][2] = 2 ;
numberArr
[2][3] = 1 ;
numberArr
[3][4] = 2 ;
int sum
= 0;
for (int[] ints
: numberArr
) {
for (int anInt
: ints
) {
if (anInt
!= 0){
sum
++ ;
}
}
}
int [][] sparseArr
= new int [sum
+1][3];
sparseArr
[0][0] = numberArr
.length
;
sparseArr
[0][1] = numberArr
[0].length
;
sparseArr
[0][2] = sum
;
int count
= 0;
System
.out
.println("原始数组为");
for(int i
=0; i
< numberArr
.length
; i
++){
for(int j
= 0; j
< numberArr
[0].length
; j
++){
if (numberArr
[i
][j
] > 0){
count
++;
sparseArr
[count
][0] = i
;
sparseArr
[count
][1] = j
;
sparseArr
[count
][2] = numberArr
[i
][j
];
}
System
.out
.printf("%d\t", numberArr
[i
][j
]);
}
System
.out
.println();
}
System
.out
.println("存盘的稀疏数组为······");
myIteator(sparseArr
);
BufferedWriter writer
= new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\上传\\map.data"));
writer
.write(String
.valueOf(sparseArr
.length
));
writer
.newLine();
for (int i
= 0; i
< sparseArr
.length
; i
++){
writer
.write(sparseArr
[i
][0]+","+sparseArr
[i
][1]+","+sparseArr
[i
][2]);
writer
.newLine();
}
writer
.close();
BufferedReader reader
= new BufferedReader(new FileReader("C:\\Users\\35022\\Desktop\\上传\\map.data"));
String firstLine
= reader
.readLine();
int [][] sparseArr2
= new int[Integer
.valueOf(firstLine
)][3];
int num
= 0;
String secondLine
= reader
.readLine();
while(secondLine
!= null
){
String
[] split
= secondLine
.split(",");
sparseArr2
[num
][0] = Integer
.valueOf(split
[0]);
sparseArr2
[num
][1] = Integer
.valueOf(split
[1]);
sparseArr2
[num
][2] = Integer
.valueOf(split
[2]);
secondLine
= reader
.readLine();
num
++;
}
reader
.close();
System
.out
.println("读盘后稀疏数组为:");
myIteator(sparseArr2
);
int [][] numberArray
= new int[sparseArr2
[0][0]][sparseArr2
[0][1]];
for (int i
=1; i
< sparseArr2
.length
; i
++){
numberArr
[sparseArr2
[i
][0]][sparseArr2
[i
][1]] = sparseArr2
[i
][2];
}
System
.out
.println("恢复的数组为......");
for(int i
=0; i
< numberArr
.length
; i
++){
for(int j
= 0; j
< numberArr
[0].length
; j
++){
System
.out
.printf("%d\t", numberArr
[i
][j
]);
}
System
.out
.println();
}
}
private static void myIteator(int[][] sparseArr2
) {
for (int i
= 0; i
< sparseArr2
.length
; i
++) {
System
.out
.printf("%d\t", sparseArr2
[i
][0]);
System
.out
.printf("%d\t", sparseArr2
[i
][1]);
System
.out
.printf("%d\t", sparseArr2
[i
][2]);
System
.out
.println();
}
}