[toc]
稀疏数组 SparseArray
1. 案例分析
稀疏数组和二维数组,使两种数据结构可以轻松的转换,从而实现五子棋程序中有存盘和续上盘的功能。
2. 代码实现
在二维数组中数组名.length指示数组的行数,数组名[行下标] .length指示该行中的元素个数。
- 二维数组转换成稀疏数组,并且储存到
map.data
中
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
| public class SparseArrayOut{ public static void main(String[] args) throws IOException{ int[][] array = new int[11][11]; array[2][1] = 1; array[2][3] = 2; array[4][5] = 2; System.out.println("原始的二维数组"); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { System.out.print(array[i][j]); } System.out.println(); } int sum = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if(array[i][j]!=0) { sum++; } } } System.out.println("这局共有"+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 <array.length; i++) { for (int j = 0; j < array.length; j++) { if(array[i][j]!=0) { count++; sparseArr[count][0]=i; sparseArr[count][1]=j; sparseArr[count][2]=array[i][j]; } } } System.out.println("得到稀疏数组为......"); File file = new File("E:/file/","map.data"); FileOutputStream fos = new FileOutputStream(file); 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]); fos.write(sparseArr[i][0]); fos.write(sparseArr[i][1]); fos.write(sparseArr[i][2]); } fos.close(); System.out.println(); } }
|
- 从
map.data
中读取数据,并将其还原成二维数组
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
| public class SparseArrayIn{ public static void main(String[] args) throws IOException{ File file = new File("E:/file/","map.data"); FileInputStream fis = new FileInputStream(file); int row = fis.read(); int col = fis.read(); int value = fis.read();
int[][] array2 = new int[row][col];
for (int i = 1; i <= value; i++) { int rows = fis.read(); int cols = fis.read(); int values = fis.read(); array2[rows][cols]=values; } fis.close();
System.out.println("恢复后的二维数组");
for (int[] rowss : array2) {
for (int data : rowss) { System.out.printf("%d\t",data);
} System.out.println(); }
} }
|