user10170761
user10170761

Reputation:

Find number of duplicate that occurs in array - Java

I can't wrap my head around this. Need to find duplicates and I did. All now that is left is to print how many times a duplicate appears in the array. I just started with Java,so this needs to be hard coded for me to understand. Spend last two days trying to figure it out but with no luck.. Any help will be great! Talk is cheap,here is the code..

import java.util.Arrays;
public class LoopTest {

    public static void main(String[] args) {

        int[] array = {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
        int positive_counter = 0;
        int negative_counter = 0;


        for (int i = 0; i < array.length; i++) {
            if(array[i] > 0) {
                positive_counter++;
            } else if(array[i] < 0) {
                negative_counter++;
            }
        }

        int[] positive_array = new int[positive_counter];
        int[] negative_array = new int[negative_counter];

        positive_counter = 0;
        negative_counter = 0;

        for (int i = 0; i < array.length; i++) {
            if(array[i] > 0) {
                positive_array[positive_counter++] = array[i];
            } else if(array[i] < 0) {
                negative_array[negative_counter++] = array[i];
            }
        }

        System.out.println("Positive array: " + (Arrays.toString(positive_array)));
        System.out.println("Negative array: " + (Arrays.toString(negative_array)));

        Arrays.sort(array);
        System.out.println("Array duplicates: ");
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if(array[i] == array[j]) {                    
                    System.out.println(array[j]);
                }

            }
        }
    }
}

Upvotes: 2

Views: 201

Answers (6)

solracq
solracq

Reputation: 1

public static void findDuplicate(String s){

char[] charArray=s.toCharArray();
ArrayList<Character> duplicateList = new ArrayList<>();
System.out.println(Arrays.toString(charArray));

for(int i=0 ; i<=charArray.length-1; i++){
    if(duplicateList.contains(charArray[i]))
        continue;
    for(int j=0 ; j<=charArray.length-1; j++){
        if(i==j)
            continue;

        if(charArray[i] == charArray[j]){
            duplicateList.add(charArray[j]);
            System.out.println("Dupliate at "+i+" and "+j);
        }
    }
}

}

Upvotes: 0

Azhy
Azhy

Reputation: 706

You can do it by creating an array list for duplicate values:-

Arrays.sort(array);
System.out.println("Array duplicates: ");

ArrayList<Integer> duplicates = new ArrayList<Integer>(); 

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        if(j != i && array[i] == array[j] && !duplicates.contains(array[i])){
            duplicates.add(array[i]);
            System.Out.println(duplicates[duplicates.size()-1]);
        }
    }
}

Upvotes: 0

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31273

From the algorithmic point of view, Veselin Davidov's answer is good (the most efficient).

In a production code, you would rather write it like this :

Map<Integer, Long> result = 
    Arrays.stream(array)
          .boxed() //converts IntStream to Stream<Int>
          .collect(Collectors.groupingBy(i -> i, Collectors.counting()));

The result is this Map :

System.out.println(result);

{0=2, 545=1, -4=1, -22=1, -87=1, -999=1, -55=1, 23=1, 43=2, 12=2}

Upvotes: 1

An easy way would be using Maps. Without changing code too much:

 for (int i = 0; i < array.length; i++) {
        int count = 0;
        for (int j = i + 1; j < array.length; j++) {
            if(array[i] == array[j]) {                    
                System.out.println(array[j]);
                count++;
            }
        }
        map.put(array[i], count);
  }

Docs: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

Edit: As a recommendation, after you are done with the example, you should analize your code and find what isn´t neccesary, what could be done better, etc.

Are all your auxiliary arrays neccesary? Are all loops necessary?

Upvotes: 0

Safwan Shaikh
Safwan Shaikh

Reputation: 546

Just go through your solution, first you separate positive and negative numbers in two different arrays, then you never use them, so what's the purpose of this separation ? I am giving you just an idea related to your problem, it's better to solve it by your self so that you can get hands on Java.

Solution: you can use Dictionary-key value pair. Go through your array, put element in dictionary as a key and value as zero, on every iteration check if that key already exist in Dictionary, just increment its value. In the end, all of the values are duplicates that occurs in your array.

Hope it helps you.

Upvotes: 1

Veselin Davidov
Veselin Davidov

Reputation: 7081

Since you are already sorting the array you can find the duplicates with just one loop (they will be next to each other right?). So you can do something like:

            Arrays.sort(array);
            System.out.println("Array duplicates: ");
            int lastValueCount=1; //How many times we met the current value (at least 1 - this time)
            for (int i = 1; i < array.length; i++){        
                    if(array[i] == array[i-1])                     
                        lastValueCount++;   //If it is the same as the previous increase the count  
                    else {
                       if(lastValueCount>1) //If it is duplicate print it
                           System.out.println(array[i-1]+" was found "+lastValueCount+" times");
                       lastValueCount=1; //reset the counter
                    }
            }

Result for your array is:

Array duplicates: 
0 was found 2 times
12 was found 2 times
43 was found 2 times

Also you can use some of the Java bells and whistles like inserting the values into Map or something like that but I guess you are looking from an algorithmic point of view so the above is the simple answer with just one loop

Upvotes: 2

Related Questions