二维数组和

时间:2011-03-27 23:27:27

标签: java arrays matrix

我有二维浮点数组,如下所示

{0.2,0.0,0.3,0.0,0.0}
{0.4,0.1,0.0,0.0,0.9}
{0.0,0.0,0.0,0.3,0.6}

我想获得以下输出

{0.6,0.0,0.3,0.0,0.0}
{0.6,0.1,0.0,0.0,1.5}
{0.0,0.0,0.0,0.3,1.5}

如果您进行分析,我会将每列的非零值相加,并使用该总和值更新所有非零值。例如,在第一列I求和(0.2 + 0.4 = 0.4)并且将值位置更新为0.6。

我正在使用Java,我该如何执行此操作?它是一个简单的例子,实时我有很大的数组。

2 个答案:

答案 0 :(得分:1)

这假设它们的长度都相同。特殊情况是对读者的锻炼。

class MatTest {
    static void makeSums(float[][] floats) {
        // we wouldn't be doing any operations on these inputs anyway, so return
        if(floats == null || floats.length == 0 || floats.length == 1) return;

        // check to make sure it's retangular
        for(float[] arr : floats) {
            if(arr.length != floats[0].length) {
                throw new IllegalArgumentException("makeSums() requires rectangular array");
            }
        }

        for(int i = 0; i < floats[0].length; i++) {
            // do each column
            float sum = 0f;
            for(int j = 0; j < floats.length; j++) {
                sum += floats[j][i];
            }
            for(int j = 0; j < floats.length; j++) {
                if(floats[j][i] != 0) floats[j][i] = sum;
            }
        }
    }

    public static void main(String[] args) {
        float[][] floats = new float[3][5];
        floats[0] = new float[] {0.2f,0.0f,0.3f,0.0f,0.0f};
        floats[1] = new float[] {0.4f,0.1f,0.0f,0.0f,0.9f};
        floats[2] = new float[] {0.0f,0.0f,0.0f,0.3f,0.6f};

        makeSums(floats);

        for(int i = 0; i < floats.length; i++) {
            for(int j = 0; j < floats[0].length; j++) {
                System.out.print(floats[i][j]);
                System.out.print(" ");
            }
            System.out.println(" ");
        }
    }
}

这是结果:

 C:\Documents and Settings\glow\My Documents>javac MatTest.java

 C:\Documents and Settings\glow\My Documents>java MatTest
 0.6 0.0 0.3 0.0 0.0
 0.6 0.1 0.0 0.0 1.5
 0.0 0.0 0.0 0.3 1.5

答案 1 :(得分:1)

让我们将您的输入数组float[][] a和并行输出数组b初始化为全零。

float curSum = 0.0;   
first = true;
for(int i = 0; i < a[0].length; i++)
{
    for(int j = 0; j < a.length; j++)
    { 
         if(a[i][j] != 0)
         {
             if (first)
             {
                 for(int k = j; k < a.length; k++)
                     curSum += a[i][k];
                 first = false;
             }
             b[i][j] = curSum;
         }
     }
     curSum = 0.0;
     first = true;
}

你可能需要改变一些更好的点,比如花车和东西的比较,但我认为这个想法就在那里

我认为它在O(n * m)中运行,并且看起来不太好,但我试图尽可能缩短迭代次数。我没有看到任何更快的方法来做到这一点。即使有三个for循环,k的循环也只会为每个j循环运行一次,所以渐渐地它根本不会增加复杂性。