1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package com.demo;
import java.awt.*; import java.io.*;
public class SparseArray { public static void main(String[] args) throws IOException {
int chessArr1[][]= new int[11][11]; chessArr1[1][2] = 1; chessArr1[2][4] = 2; chessArr1[0][0] = 2; for (int[] row : chessArr1){ for(int data : row){ System.out.printf("%d\t",data); } 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]; sparseArr[0][0] = 11; sparseArr[0][1] = 11; sparseArr[0][2] = sum;
int count = 0; for (int i = 0; i <11; i++) { for (int j=0;j<11;j++){ if (chessArr1[i][j] != 0){ count++; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr1[i][j];
} } } File file = new File("D:\\My文档\\IDEAdemo\\hexo-boot-2.3.0\\algorithm"+File.separator+"chess.data"); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter write = new OutputStreamWriter(fos, "UTF-8");
System.out.println(); System.out.println("稀疏数组:"); for (int i = 0; i < sparseArr.length; i++) { System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
if (i == sparseArr.length - 1) { write.append(sparseArr[i][0] + "," + sparseArr[i][1] + "," + sparseArr[i][2]); } else { write.append(sparseArr[i][0] + "," + sparseArr[i][1] + "," + sparseArr[i][2] + ","); } }
System.out.println("写入文件中..."); write.close(); fos.close();
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]]; for (int i = 1; i <sparseArr.length; i++) { chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("打开文件中..."); Desktop.getDesktop().open(file);
System.out.println("------------------------------先读取_chess.data"); FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis, "UTF-8"); StringBuffer sb = new StringBuffer(); while (reader.ready()) { sb.append((char) reader.read()); }
System.out.println(sb.toString()); reader.close(); fis.close();
System.out.println("恢复后的数组"); for (int[] row : chessArr2) { for (int data : row){ System.out.printf("%d\t",data); } System.out.println();
} } }
|