關注 “弋凡”(YiFan)微信公衆號吧 記錄簡單筆記 做你的最愛
1,定義
稀疏數組可以看作普通二維數組的壓縮,這裏的普通數組指無效數據遠大於有效數據
稀疏數組分爲3
列
行 列 值
r1 c1 v1
r2 c2 v2
... ... ...
普通二維數組 - 無效數據遠遠大於有效數據
0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 0 2 0 2 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
稀疏數組
11 11 3
1 1 1
2 2 2
2 4 2
2,代碼實現
package com.yifan.nolinear;
import java.io.*;
/**
* @Author YIFan
* @Date 2020/6/7 17:49
* @Version 1.0
*/
// 稀疏數組
public class SparseArray {
public static void main(String[] args) throws IOException {
// 創建一個二維數組 11*11
// 0 表示沒有數組 1 表示黑子 2 表示 白子
int[][] chessArry = new int[11][11];
chessArry[1][1] = 1;
chessArry[2][2] = 2;
chessArry[2][4] = 2;
// 輸錯原始數組
System.out.println("原始數組...");
for (int[] row : chessArry) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
int sum = 0;
//將二維數組轉化爲稀疏數組
//1,二維數組得到非零數據的個數
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArry[i][j] != 0 ){
sum++;
}
}
}
//2,創建對應的稀疏數組
int sparseArr[][] = new int[sum+1][3];
// 給稀疏數組賦值
// 行數
sparseArr[0][0] = 11;
// 列數
sparseArr[0][1] = 11;
// 有效數
sparseArr[0][2] = sum;
//3,遍歷二維數組,將非0的值存到sparseArr中
//------> (稀疏數組格式) 行 列 值
int count = 0; // 用於記錄第幾個是非0數據
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArry[i][j] != 0 ){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArry[i][j];
}
}
}
//4,輸出稀疏數組
System.out.println();
System.out.println("稀疏數組爲....");
//寫入到文件中
File file = new File("d:/a.data");
FileOutputStream in = new FileOutputStream(file);
for (int i = 0; i < sparseArr.length; i++) {
String str = sparseArr[i][0]+"-"+sparseArr[i][1]+"-"+sparseArr[i][2]+"\n";
in.write(str.getBytes());
System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
}
System.out.println("寫入文件成功...");
in.close();
//5,將稀疏數組還原成原始的二維數組
/*
* 1,先讀取稀疏數組的第一行,根據第一行數據,創建原始的二維數組
* 2,在讀取稀疏數組的後幾行數據,並賦值給二維數組
* */
// int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
// 從文件中讀取
int[][] chessArr2 = null;
BufferedReader reader = null;
System.out.println("以行爲單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null爲文件結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
System.out.println("line " + line + ": " + tempString);
String[] split = tempString.split("-");
int row = Integer.parseInt(split[0]);
int col = Integer.parseInt(split[1]);
if(line==1){
chessArr2 = new int[row][col];
}else {
chessArr2[row][col] = Integer.parseInt(split[2]);
}
line++;
}
reader.close();
// 用稀疏數組進行還原
// for (int i = 1; i < sparseArr.length; i++) {
// int row = sparseArr[i][0];
// int col = sparseArr[i][1];
// chessArr2[row][col] = sparseArr[i][2];
// }
System.out.println("新的二維數組...");
for (int[] row : chessArr2) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}