1、数组主要的元素大部分为0时,为避免浪费空间,将数组变成稀疏数组
实现方式:
1)记录数组一共有几行几列,有多少个不同的值(第一行)
2)把具有不同值的元素的行、列、值记录在一个小规模的数组中,进而缩小程序的规模
3)其他行代表几个不同值的存放位置,原数组的行,原数组的列,原数组的值
稀疏数组示例:
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class SparearrayChess {
public static void main(String[] args) {
// 创建一个原始的二维数组
// 0:表示没有棋子1:表示黑子2:表示蓝子
int chessarry[][] = new int[11][11];
// 输入数据型
Scanner scanner = new Scanner(System.in);
int r = 0;
while (true) {
r = scanner.nextInt();// 确定第几行
if (r == -1) {
break;
}
int c = scanner.nextInt();// 确定第几列
int value = scanner.nextInt();// 输入值
chessarry[r][c] = value;
}
// chessarry[1][2] = 1;
// chessarry[2][3] = 2;
// 输出原始的二维数组
System.out.println("原始的二维数组");
for (int[] row : chessarry // 先读取行,存入到一个一维数组中
) {
for (int data : row
) {
System.out.printf("%d\t", data); // 读取行中的数据
}
System.out.println();
}
// 转换为稀疏数组
// 获取有效的值的个数
int sum = 0;
// 扫描当前的数组进行一个判断非0个数
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessarry[i][j] != 0) {
sum++;// 非0的栏位
}
}
}
// 创建稀疏数组
int sparsearray[][] = new int[sum + 1][3];
// 对稀疏数组进行赋值
// 第一行存放 二维数组的规格、
sparsearray[0][0] = 11;
sparsearray[0][1] = 11;
sparsearray[0][2] = sum;
// 对之后的值进行赋值
int count = 0; // 记录其中的行
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessarry[i][j] != 0) {
count++;
sparsearray[count][0] = i;
sparsearray[count][1] = j;
sparsearray[count][2] = chessarry[i][j];
}
}
}
// 对稀疏数组进行格式化输出
System.out.println("稀疏数组为~~~~");
StringBuffer s = new StringBuffer();
for (int i = 0; i < sum + 1; i++) {
s.append(sparsearray[i][0]+"\t"+ sparsearray[i][1]+"\t" + sparsearray[i][2]+"\n");
System.out.printf("%d\t%d\t%d\t\n", sparsearray[i][0], sparsearray[i][1], sparsearray[i][2]);
}
/*
对稀疏数组进行存盘操作
*/
FileOutputStream f = null;
try {
f = new FileOutputStream("D:\\网站下载站\\五子棋.txt ",true);
byte[] bytes = String.valueOf(s).getBytes(StandardCharsets.UTF_8);
f.write(bytes);
// 最后要进行刷新
f.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}finally{
if(f != null){
try {
f.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/*
int chessarray3[][] = new int[sum + 1][3];
// 将数据从盘中取出,转换为稀疏数组
FileInputStream f2 = null;
try {
f2 = new FileInputStream("D:\\网站下载站\\五子棋.txt ");
int readDate;
int cout = 0;
while((readDate = f2.read())!=-1){
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if(f2 != null){
try {
f2.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
*/
System.out.println();
// 将稀疏数组进行恢复
// 1 获取原始二维数组的规格为多少
int chessarray2[][] = new int[sparsearray[0][0]][sparsearray[0][1]];
// 2 对二维数组进行赋值
for (int i = 1; i < sparsearray[0][2] + 1; i++) {
chessarray2[sparsearray[i][0]][sparsearray[i][1]] = sparsearray[i][2];
}
// 3 对二维恢复数组进行输出
System.out.println("恢复的的二维数组");
for (int[] row : chessarray2 // 先读取行
) {
for (int data : row
) {
System.out.printf("%d\t", data); // 读取行中的数据
}
System.out.println();
}
}
}