Question

I have to create a decompress method that is passed a compressed array of shorts created from another method in my program. It's basically RLE, with the first value being the number of times a value is repeated and the second being the value itself.

I'm not the best with for loops or arrays - I'm really trying to get better - so this last part of my assignment is throwing me off. Can anyone help or point me in the right direction?

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;
}

I know that I have to assign the incoming values to the new array - "dcmpArray" - and that should be done inside the for loop. I'm having problems on separating the values and then determining how many times the value should be printed in the new array. I was going to use "position" to determine the position in which index the value should be printed, but I'm having a brain fart..

Was it helpful?

Solution

I'm not sure why your array would be 2 dimensional, but for a 1-dimensional array containing a series of shorts with RLE like you specify, this would be how to decompress it:

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;
}

If your 2-dimensional array is simply an array of input arrays, then simply perform that procedure on each of the input arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top