Reputation: 1347
I have a 2d array String compressedColors[][]
, which is filled with numbers between 0 and n(Where n is the number of colors in an image). Now I'm trying to compress my array even more for writing to a file, and one idea I had is replacing consecutive identical elements with some sort of multiplication operator. As in I'd like:
compressedColors[0][0]=="1"
compressedColors[0][1] == "1"
to become
compressedColors[0][0]=="2*1"
compressedColors[0][1] == ""
This would need to happen for large numbers of consecutive idenitcal elements, and I only want the compression to go across the second dimension of the array. If two rows are filled with 0's, I want 2 seperate n*0
values at compressedColors[x][0]
.
I know this is asking a lot, but any ideas how I could accomplish this? I don't even know where to start... Thanks!
Upvotes: 0
Views: 58
Reputation: 4148
To answer your question you need to implement both compression and de-compression.
The algorithm for compression (thanks @harold for the term "run-length encoding"), would be something like:
// for an uncompressed image of height h and width w, stored in int colors[][]
for row = 0 to height
for column = 0 to width
// gets the value
value = colors[row][column]
// calculates how long the value repeats
runLength = 0
nextValue = value
i = 0
while(nextValue == value)
i++
runLength++
nextValue = colors[row][column + i]
// sets the runlength and the value
compressedColors[row][column] = runLength
compressedColors[row][column + 1] = value
// moves to next different value
column = column + runLength
Then, to decompress, you need to interpret every odd column as a run-length and every even column as a value.
Upvotes: 1
Reputation: 2047
I wrote an example which should at least give you an idea how to achieve a solution to your problem. I didn't have a chance to test this out right now so I'm not sure if this will work without modifications.
public static String[][] compress(String[][] sArray){
for(String s[] : sArray){
int current = 0;
while(current <= s.length){
int sequentials = 1;
while(s[current].equals(s[current+sequentials])){
s[current+sequentials] = "";
sequentials++;
if(current+sequentials>s.length)
break;
}
if(sequentials > 1) s[current] = sequentials+"*"+s[current];
current++;
}
}
return sArray;
}
Upvotes: 1