My goal is to save space occupied by 2D array (sea) that has 3 different values.
Ocean sea; //Ocean class has member 'private int[][] oceanMatrix;'
public final static int EMPTY = 1;
public final static int SHARK = 2;
public final static int FISH = 3;
by compressing it and place in two one dimensional array.
int[] runType = new int[10]; // each cell stores 1 or 2 or 3
int[] runLength = new int[10]; // corresponding index cell stores its number of occurence of that respective runType.
I am using Runlength
encoding idea and wrote below code, which is yet to be fit into a Java class.
I need feedback/critiques on this logic of the below code and coding style, so that I can optimize and make it better. Constraint is to not use any existing Java library class except (array's length member).
private static int[] doubleTheSize(int[] arg){
int[] temp = new int[2*arg.length];
for(int c = 0; c < arg.length; c++){
temp[c] = arg[c];
}
return temp;
}
public static void main(String[] args) {
Ocean sea;
int[] runType = new int[10];
int[] runLength = new int[10];
int index = 0;
boolean firstCell = true;
//i&j are width & height of a 2d array read from commandline
for(int row = 0; row < j ; row++){
for(int col = 0; col < i ; col++){
if(firstCell){
firstCell=false;
runType[index] = sea.cellContents(0, 0);
runLength[index]++;
continue;
}
switch(sea.cellContents(row, col)){
case Ocean.EMPTY:
if(runType[index] == Ocean.EMPTY){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.SHARK;
runLength[index]++;
}
break;
case Ocean.SHARK:
if(runType[index] == Ocean.SHARK){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.SHARK;
runLength[index]++;
}
break;
case Ocean.FISH:
if(runType[index] == Ocean.FISH){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.FISH;
runLength[index]++;
}
break;
}// end switch
}//end inner for loop
}//end outer for loop
}//end main()
I wrote the above code for that. Please help me review this code for optimization. One point that I recognized is, firstCell
check that I did for every cell doesn't make sense. I need suggestion to better this logic because I need to enter in firstCell i{}
block for only (0,0) cell.
//i&j are width & height of a 2d array
.... but I say I&J are Fish in the Ocean ;-) – rolfl 20 hours ago