圖示原始陣列和稀疏陣列的轉換過程
程式碼實現
public class SparseArray {
public static void main(String[] args) throws Exception {
// 1. 建立原始陣列
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[4][5] = 2;
// 1.1 遍歷輸出原始陣列
System.out.println("原始陣列:");
travarseArrayPrint(chessArr1);
// 2. 將原始陣列轉換為稀疏陣列
// 2.1 定義變數記錄原始陣列中非0元素的個數
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
// 2.2 建立稀疏陣列並給稀疏陣列賦值
int[][] sparseArr = new int[sum + 1][3];
// 2.3 給稀疏陣列的第一行賦值
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1[0].length;
sparseArr[0][2] = sum;
// 2.4 定義變數記錄稀疏陣列的行數
int count = 0;
// 2.5 給稀疏陣列第一行之後的行賦值
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
// 2.6 遍歷輸出稀疏陣列
System.out.println("稀疏陣列:");
travarseArrayPrint(sparseArr);
// 2.7 將稀疏陣列存入到磁碟檔案
File file = new File("data.txt");
FileWriter fw = new FileWriter(file);
for (int[] row : sparseArr) {
for (int i : row) {
fw.write(i + "\t");
}
fw.write("\r\n");
}
fw.close();
// 3. 恢復原始陣列
// 3.1 從磁碟檔案中讀取稀疏陣列
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
// 記錄讀取的單行字串
String line;
// 記錄讀取的當前的行數
int row = 0;
while((line = br.readLine()) != null) {
row++;
}
br.close();
// 3.2 建立稀疏陣列
BufferedReader br1 = new BufferedReader(new FileReader("data.txt"));
int[][] sparseArr1 = new int[row][3];
row = 0;
while((line = br1.readLine()) != null) {
String[] temp = line.split("\t");
for(int i = 0; i < temp.length; i++) {
sparseArr1[row][i] = Integer.parseInt(temp[i]);
}
row++;
}
br1.close();
System.out.println("從磁碟讀進來的稀疏陣列:");
travarseArrayPrint(sparseArr1);
// 3.3建立原始陣列並根據從磁碟讀取的稀疏陣列恢復原始陣列
int[][] chessArr2 = new int[sparseArr1[0][0]][sparseArr1[0][1]];
for (int i = 1; i < sparseArr1.length; i++) {
for (int j = 0; j < sparseArr1[0].length; j++) {
chessArr2[sparseArr1[i][0]][sparseArr1[i][1]] = sparseArr1[i][2];
}
}
// 3.4 遍歷輸出恢復之後的原始陣列
System.out.println("恢復之後的原始陣列:");
travarseArrayPrint(chessArr2);
}
private static void travarseArrayPrint(int[] ...array) {
for (int[] row : array) {
for (int i : row) {
System.out.printf("%d\t", i);
}
System.out.println();
}
}
}