【问题标题】:Number of times a value occurs in each column of a 2d-array in Java?Java中二维数组的每一列中出现值的次数?
【发布时间】:2016-02-25 03:16:48
【问题描述】:
ArrayList<Integer> newArray = new ArrayList<>(); 
for (int i =0; i < count; i++) {
    newArray.add(i);       
}
for (int j = 0; j <= 3; j++) {
    Collections.shuffle(newArray);
    System.out.println(newArray.toString());
}

//Let count equal 4 since we want a square

int[][] counters = new int[count][count];
int numAppear = 0;
int row = 0;
int col = 0;
for (row = 0; row < count; row++) {

    for (col = 0; col < count; col++) {
        if (newArray.get(row).equals(newArray.get(col))) {
            numAppear++;
        }
        counters[row][col] = numAppear;

        System.out.print(counters[row][col]+" "); 
    } 
    System.out.println();
}

在代码中,我想知道如果我访问第 i 行的第 j 列,对于所有 shuffle,i 出现在 ArrayList 中的索引 j 处的次数。

另外,我正在尝试打印计数器数组,但我得到了内存哈希,尽管我尝试了 .toString 以及 Arrays.toString

假设这是我的洗牌数组输出:

[3, 1, 2, 0]
[2, 0, 1, 3]
[1, 3, 2, 0]
[0, 1, 2, 3]

现在为 counters[row][col] = numAppear 输出;应该是这样的: 第一行:因为 shuffle 数组的 row0 = col0,numAppear = 1。

第三行在 (2,2) 中有一个 2,因为在 (2,2) 的洗牌数组中,#2 在同一列中出现了两次,但在前几行中

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

【问题讨论】:

    标签: java arrays multidimensional-array printing


    【解决方案1】:

    你为什么使用 'counters[row][col] = numAppear;' ?

    如果只是为了最终计算它,请在开始迭代元素之前初始化另一个 int 计数器。

    由于“numAppear”值在匹配之间持续存在,我看不到将 temporary“numAppear”值添加到数组中的值。 如果我理解您的打印声明的目标,这可能是一个可行的选择:

    System.out.println("在行" + row + "和列" + col)找到匹配;

    编辑:至于打印匹配,我会在开始时初始化一个数组列表并在最后迭代它。例如:

        ArrayList<String> matchList = new ArrayList<String>();
    

    添加:

        matchList.add(numAppear);//or whatever you're trying to add
    

    然后在最后:

        for (String s : matchList){
            System.out.println("Match at: " + s);
        }
    

    【讨论】:

    • 感谢您的回复。我将更新我的输出在原始帖子中的样子。
    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 2021-09-02
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2022-01-07
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多