我有一个2d数组String compressedColors[][]
,它填充0到n之间的数字(其中n是图像中的颜色数)。现在我正在尝试压缩我的数组甚至更多写入文件,我有一个想法是用某种乘法运算符替换连续的相同元素。就像我想的那样:
compressedColors[0][0]=="1"
compressedColors[0][1] == "1"
成为
compressedColors[0][0]=="2*1"
compressedColors[0][1] == ""
这需要在大量连续的idenitcal元素中发生,我只希望压缩跨越数组的第二维。如果两行填充0,我想在n*0
处有两个单独的compressedColors[x][0]
值。
我知道这是在问很多,但任何想法我怎么能做到这一点?我甚至不知道从哪里开始...... 谢谢!
答案 0 :(得分:1)
我写了一个例子,至少应该让你知道如何解决你的问题。我现在没有机会对此进行测试,所以我不确定这是否会在没有修改的情况下运行。
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;
}
答案 1 :(得分:1)
要回答您的问题,您需要实施压缩和解压缩。
压缩算法(感谢@harold用于术语&#34;游程编码&#34;),如下所示:
// 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
然后,要解压缩,您需要将每个奇数列解释为游程长度和每个偶数列作为值。