将二维数组缩放两倍

Scaling a 2D array by a factor of two

该程序应该将每个单元格中包含对象的数组缩放为两倍。例如数组:

[[Object1,Object2],
 [Object3,Object4]]

应该变成:

[[Object1,Object1,Object2,Object2],
 [Object1,Object1,Object2,Object2],
 [Object3,Object3,Object4,Object4],
 [Object3,Object3,Object4,Object4]]

这是我目前的程序代码:

public Color[][] doOperation(Color[][] imageArray)
{
    int multiplier = 2;  
    Color[][] newArray = new Color[imageArray.length*2][imageArray[0].length*2];

    for(int i = 0; i < imageArray.length; i++)
        for(int j = 0; j < imageArray[0].length; j++)
        {
            newArray[i][j] = imageArray[i/multiplier][j/multiplier];
        }
}

我应该如何更改此代码以便正确缩放新数组?感谢任何帮助。

您应该循环 newArray,而不是 imageArray

示例:

    int[][] oldArray = new int[2][2];
    int k = 1;
    for(int i = 0; i < oldArray.length; i++)
        for(int j = 0; j < oldArray[0].length; j++)
            oldArray[i][j] = k++; 

    int[][] newArray = new int[oldArray.length*2][oldArray[0].length*2];

    for(int i = 0; i < newArray.length; i++)
        for(int j = 0; j < newArray[0].length; j++)
            newArray[i][j] = oldArray[i/2][j/2];

    System.out.println(Arrays.deepToString(oldArray));
    System.out.println(Arrays.deepToString(newArray));

输出:

[[1, 2], [3, 4]]
[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]

您混淆了 newArrayimageArray。您初始化双倍大小的 newArray(这是正确的),然后使用 imageArray 长度对其进行迭代。只需将 imageArray.length 换成 newArray.length。别忘了 return ;)

public static Color[][] doOperation(Color[][] imageArray) {
    int multiplier = 2;
    Color[][] newArray = new Color[imageArray.length*2][imageArray[0].length*2];

    for(int i = 0; i < newArray.length; i++)
        for(int j = 0; j < newArray[0].length; j++) {
            newArray[i][j] = imageArray[i/multiplier][j/multiplier];
        }
    return newArray;
}