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
| package sparsearray;
public class Sparsarray { public static void main( String args[] ) { int [][] chararray = new int [11][11]; chararray [1][2] = 1; chararray [2][3] = 2; chararray [5][6] = 2; for(int[] row : chararray) { for(int item : row) { System.out.printf("%d\t",item); } System.out.println(); } int sum = 0; for(int i = 0; i <11 ; i++) { for(int j = 0; j < 11; j++) { if (chararray[i][j] != 0) { sum++; } } }
int [][] sparse = new int[sum+1][3]; sparse[0][0] = 11; sparse[0][1] = 11; sparse[0][2] = sum; int count = 0; for(int i = 0; i <11 ; i++) { for(int j = 0; j < 11; j++) { if (chararray[i][j] != 0) { count ++; sparse[count][0] = i; sparse[count][1] = j; sparse[count][2] = chararray[i][j]; } } } System.out.println("-------------------------------"); for(int [] item : sparse) { for(int a : item) { System.out.printf("%d\t",a); } System.out.println(); } System.out.println("--------------------"); int [][] chararray2 = new int[sparse[0][0]][sparse[0][1]]; for(int i = 1;i < sum+1;i++) { chararray2[sparse[i][0]][sparse[i][1]] = sparse[i][2]; } for(int[] row : chararray2) { for(int item : row) { System.out.printf("%d\t",item); } System.out.println(); } } }
|