-1

嗨,我正在尝试计算二维数组的频率。我正在尝试以某种方式显示频率,例如,如果表格如下:

0:1 2 0

1:2 0 1

2:1 0 2

我希望能够像这样计算频率:

0:0 2 1

1:2 0 1

2:1 1 1

所以表格应该是多少次 0 出现在第一列中,多少次 1 出现在第一列中,依此类推。我不确定我有什么问题。我注意到它进入第二次迭代它停止工作或者它只是给出 0

到目前为止我的代码是

    for (int col =0; col< s ; col++){
        System.out.print(col+ ": ");
        for (int row = 0; row<s; row++)
        {
            x=val[row][col];
            if (table[row][col]==row)
            {
                System.out.print(x++ + " ");
            }

            //System.out.print(val[col][row]+" ");
            if (row+1==s)
                System.out.println();
        }
    }




}

谢谢

4

1 回答 1

0

假设一个规则形状的数组。为了使其更健壮,您需要检测最大列数。

int[][] table = new int[][]{{1,2,0},{2,0,1},{1,0,2}};
int[][] result = new int[table.length][table.length];
for (int row = 0; row<result.length;row++){
  Arrays.fill(result[row], 0);
}

// iterating through multi dimensional arrays it is easier to start
// with dimension 0
for (int row = 0; row<table.length;row++){
  for (int col =0; col< table[row].length ; col++){
    // the row in the result table equals the value of the cell.
    int index = table[row][col];
    result[index][col]++;
  }
}

System.out.println(Arrays.deepToString(result));
于 2013-04-09T08:02:31.230 回答