Sparse array, as a way to compress normal array
import java.util.Arrays;
/**
* 1, the number of rows in the original array, the number of columns, the number of all the non-data 0
* 2, data of all non-zero coordinates (row, column)
*/
public class SparseArray {
public static int [] [] toSparseArray ( int [] [] Array) {
// find all non-zero number of data
int ValueCount = 0 ;
for ( int I = 0; I <be array.length; I ++ ) {
for ( int J = 0; J <Array [I] .length; J ++ ) {
int value = Array [I] [J];
IF (! value = 0 ) {
valueCount++;
}
}
}
// initialize the sparse set of the first row pixel data, the recording of the original array row / column / ValueCount
int [] [] = SparseArray new new int [ValueCount +. 1] [. 3 ];
sparseArray[0][0] = array.length;
sparseArray[0][1] = array[0].length;
sparseArray[0][2] = valueCount;
// sparse coordinates of all non-zero pixel data sets
int index = 0 ;
for ( int I = 0; I <be array.length; I ++ ) {
for ( int J = 0; J <Array [I] .length; ++ J ) {
int value = Array [I] [J];
IF ! (value = 0 ) {
index++;
sparseArray[index][0] = i;
sparseArray[index][1] = j;
sparseArray[index][2] = value;
}
}
}
return sparseArray;
}
public static int [] [] toArray ( int [] [] SparseArray) {
// The first line of data, initialization of the original array
int [] [] Array = new new int [SparseArray [0] [0]] [SparseArray [ 0] [1 ]];
// assignment
for ( int I = 1; I <sparseArray.length; I ++ ) {
int Row SparseArray = [I] [0 ];
int column SparseArray = [I] [1 ];
int value = SparseArray [I] [2 ];
array[row][column] = value;
}
return array;
}
public static void main(String[] args) {
int originalArray[][] = new int [7][8];
originalArray[0][1] = 8;
originalArray[1][2] = 9;
toString(originalArray);
int[][] sparseArray = toSparseArray(originalArray);
toString(sparseArray);
int[][] array = toArray(sparseArray);
toString(array);
}
private static void toString(int[][] array) {
for (int i = 0 ;i < array.length; i ++) {
System.out.println(Arrays.toString(array[i]));
}
}
}