我必须创建一个解压缩方法,该方法传递从程序中的另一个方法创建的压缩的短裤数组。它基本上是 RLE,第一个值是值重复的次数,第二个值是值本身。
我在 for 循环或数组方面并不是最好的 - 我真的很想变得更好 - 所以我作业的最后一部分让我感到失望。谁能帮助我或为我指明正确的方向?
public static short[][] decompress(short[][] cmpArray){
int position = 1;
short[][] dcmpArray = new short[cmpArray.length][cmpArray.length];
for(int i=0; i<cmpArray.length; i++){
for(int j=0; j<cmpArray[0].length; j++){
}
}
return dcmpArray;
}
我知道我必须将传入值分配给新数组 - “dcmpArray” - 这应该在 for 循环内完成。我在分离值然后确定该值应在新数组中打印多少次时遇到问题。我本来打算使用“位置”来确定应在哪个索引中打印该值的位置,但我脑子里放屁了..
最佳答案
我不确定为什么你的数组是二维的,但对于包含一系列像你指定的 RLE 的短裤的一维数组,这将是如何解压缩它:
public static short[] decompress(short[] input) {
int outputLength = 0;
/* First we need to figure out how long the output is
going to be when uncompressed, so we iterate through
the input like we are would normally, but write no output,
instead computing the output length */
//note the += 2; we want to skip the actual output
for(int i = 0; i < input.length; i += 2) {
outputLength += input[i]; //increment target length
}
/* Now that we know what the output size will be,
we can create an array to store it. */
short[] output = new short[outputLength];
/* Now iterate over the input, putting every other input short
into the output, duplicated the number of times of the current input
AKA: decompression of RLE */
for(int i = 0, outOffset = 0; i< input.length; i += 2) {
for(int ii = 0; ii < input[i]; ii++)
output[ii + outOffset++] = input[i + 1];
}
return output;
}
如果您的二维数组只是一个输入数组的数组,则只需对每个输入数组执行该过程即可。
关于java - 如何使用 for 循环解压缩 Shorts[][] 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976394/