java - 如何使用 for 循环解压缩 Shorts[][] 数组?

标签 java arrays for-loop compression

我必须创建一个解压缩方法,该方法传递从程序中的另一个方法创建的压缩的短裤数组。它基本上是 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/

相关文章:

数组破坏了 Julia 中的字符串类型

Javascript迭代高亮

r - 如何在 R 环境中循环遍历编号数据帧。我必须在 R 中循环 22 个(可能是 22*6)数据帧

java - Hibernate搜索可以与eclipse JPA提供程序一起使用吗?

java - 当键盘出现时 Android 布局被换行

java - 遍历Hash Map key的值是按降序还是升序?

java - 使用回滚时事务测试方法不抛出异常

ruby - 如何通过 Ruby 中的索引从数组中获取多个值

c# - 如何在 1D 数组中使用 "flatten"或 "index"3D 数组?

javascript - 如何使用 lodash _.filter 与 _.forEach 重构 for 循环?