简体   繁体   中英

Number of times a value occurs in each column of a 2d-array in Java?

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();
}

In the code, I want to find how many times if i visit column j of row i, i appears at index j in the ArrayList for all the shuffles.

Also, I'm trying to print counter array, but i get memory hashes although i tried .toString as well as Arrays.toString

Let's say this is my output for shuffled array:

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

Now output for counters[row][col] = numAppear; should look like this: First row:since row0 = col0 of shuffled array, numAppear = 1.

Third row there's a 2 in (2,2) because in (2,2) of shuffled array, #2 appears twice in the same column but in the previous rows

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

Why are you using 'counters[row][col] = numAppear;' ?

If it's just to eventually count it, initialize another int counter before you start iterating through the elements.

Since "numAppear" value persists between matches, I don't see the value in adding the temporary "numAppear" value to an array. If I understand the goal of your print statement, this might be a viable alternative:

System.out.println("Found a match at row " + row + " and column " + col);

Edit: As for printing the matches, I'd initialize an array list at the outset and iterate through it at the end. eg:

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

To add to it:

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

Then at the end:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM