I am trying to loop through my array and find all the numbers that are repeating more than once:
E.G: if there is 1 1 2 3 4
It should print saying "1 repeats more than once"
Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9
, it will print all the 4's but i dont want that:
class average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
File myFile = new File("num.txt");
Scanner Scan = new Scanner(myFile);
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
Scan.close();
Scan = new Scanner(myFile);
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
Scan.close();
Scan = new Scanner(myFile);
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
System.out.println(buffer[k]);
}
}
}
Just add the number you will find duplicated to some structure like
HashSet
orHashMap
so you can find it later when you will detect another duplication.Better O(n) alghorithm:
Using the apache commons CollectionUtils.getCardinalityMap(collection):
toString() of cardinalityMap looks like this after the init:
Using standard java:
You perform the check for every single item of the array, including the first
4
, the second4
and so on. That's why it just doesn't stop and it prints the message multiple times per duplicated element.You're saying you cannot use a
Set
and that you don't want to sort your data. My suggestion is that you loop over the array and add each duplicated item to a list. Make sure you check whether the item has already been added. (or use aSet
:) )Then loop over the list and print those items.
This problem is much simpler and likely faster to solve using a collection. However, as requested here's an answer that uses "just simple array[s]" and no sorting. I've tried not to change your code too much but I refuse to leak resources in the case of an exception.
Input file "num.txt" (numbers separated by newlines not commas):
Output:
I would use a
HashMap
to store the value I encounter in the array, with the count as a value. So if you encounter a 4, you would look it up in theHashMap
, if it doesn't exist, you would add it with a value of 1, otherwise increment the value returned.You can the loop over the
HashMap
and get all the values and print the number of duplicates encountered in the array.Output: [1, 2, 3, 4]