Reputation: 13
Im trying to create a java method that will look at a 2d array and see how many times a number has been entered more than once and then output the count.
So given this array
1 2 3 3
5 6 7 8
8 45 9 45
10 17 18 13
the method will return a count of 3
.
So far this is what i have
int dupe=0;
int chk1=0, chk2=0;
for (int row =0; row < dataTable.length; row ++)
{//for 1
for ( int col = 0; col < dataTable[row].length; col++)
{//for 2
if (dataTable[row][col] == dataTable [chk1][chk2])
{//if
dupe++;
}//end if
chk1++;
chk2++;
}//end for 2
}//end for 1
dupe=dupe-1;
return dupe;
however it will not run unless i declare chk1 and chk2 inside the second 4 which just re declares them every time the check is run.
Upvotes: 0
Views: 3767
Reputation: 109613
Two interpretations:
/**
* The number of entries that are double of others.
* When 4 threes occure, 3 threes are counted.
*/
public static int moreThanOnce(int[][] matrix) {
Set<Integer> uniqueNumbers = new HashSet<Integer>();
int n = 0;
for (int row = 0; row < matrix.length; ++i) {
n += matrix[i].length;
Collections.addAll(uniqueNumbers, matrix[i]);
}
return n - uniqueNumbers.size();
}
/**
* The number of different numbers appearing more than once.
* When four appears 3 times and eight 4 times, then the result is 2.
*/
public static int moreThanOnce2(int[][] matrix) {
Set<Integer> usedNumbers = new HashSet<Integer>();
Set<Integer> doubleNumbers = new HashSet<Integer>();
for (int[] row : matrix) {
for (int x : row) {
if (!usedNumbers.add(x)) { // Not added, already used
doubleNumbers.add(x);
}
}
}
return doubleNumbers.size();
}
Upvotes: 0
Reputation: 129
Well you could loop through the array by looking through every row...
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
// check
}
}
And then check if a number has been repeated by comparing it to all the other numbers, which you can store somewhere else.
Upvotes: 0
Reputation: 106508
Strategy: Iterate over the entire array, and compare each element to all other elements. Gather the results in a variable. Since I think that this is homework, I can't give you the code, but the strategy should be enough to get you started.
Upvotes: 1
Reputation: 56779
How it might be implemented:
Upvotes: 4