I need to count the number of dupes in an array, but I'm constrained to only using arrays, no HashSets or ArrayLists.
Here are example inputs with their expected outputs:
numDuplicates(new double[] { }) --> 0
numDuplicates(new double[] { 11.0 }) --> 0
numDuplicates(new double[] { 11.0, 11.0, 11.0, 11.0 }) --> 3
numDuplicates(new double[] { 11.0, 11.0, 11.0, 11.0, 22.0, 33.0, 44.0, 44.0, 44.0, 44.0, 44.0, 55.0, 55.0, 66.0, 77.0, 88.0, 88.0 }) --> 9
numDuplicates(new double[] { 11.0, 22.0, 33.0, 44.0, 44.0, 44.0, 44.0, 44.0, 55.0, 55.0, 66.0, 77.0, 88.0 }) --> 5
This is the code I have, but it counts duplicates after each number, returning an inflated count, i.e. {11.0, 11.0, 11.0, 11.0} returns 6 instead of 3:
public static int numDuplicates (double[] list) {
int dupCount = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] == list[j]) {
dupCount++;
}
}
}
return dupCount; //TODO1: fix this
}
Note: I'm new on Stack, I tried searching thoroughly but couldn't find an array duplicate question that had similar input/output to mine, but I'm sorry if someone has already asked this.