Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to search through an array of n numbers and find the numbers that are repeated. So far I have this code, which does the job, but I find it to be a rather cumbersome method, but I can't seem to find another method of doing it.

class Checknumber{
    int [] numbers = new int [5];
    Scanner inn = new Scanner(System.in);
    boolean b = true;
    int temp = -1;

    void sjekk(){
        System.out.println("Write five numbers");
        for(int i = 0; i < numbers.length; i++){
        numbers [i] = inn.nextInt();
    }

    //sjekker om det er like tall i arrayen
    System.out.print("\nNumbers that are repeated: ");
    for(int i = 0; i < numbers.length; i++){

        if(!b){
            System.out.print(temp + " ");
        }

        b = true;
        temp = numbers[i];
        for(int j = 0; j < numbers.length; j++){
            if(i != j && temp == numbers[j] && numbers[j] != -2){
                b = false;
                numbers[j] = -2;
            }
        }
    }

}
share|improve this question
You should tag the language you're using. – Asad Nov 23 '12 at 15:19
Do you mean dupplicate numbers, or a set of identical numbers in a series? Should that eliminate the last "1" in "1231", or the "3" in "12333333456" ? – AlexWien Nov 23 '12 at 15:27
1  
Another possibility is to sort the array first, for example using Arrays.sort(). This would bring any repeated numbers next to each other, simplifying the logic needed to find and print them out. – NPE Nov 23 '12 at 15:28
I should have been more clear. If I have a set "1 2 3 2 1" then I want the program to print out: "These numbers are repeating: 1 and 2" – Hatori Sanso Nov 24 '12 at 0:44

migrated from stackoverflow.com Nov 23 '12 at 15:53

This question came from our site for professional and enthusiast programmers.

5 Answers

int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };
Arrays.sort(numbers);

for(int i = 1; i < numbers.length; i++) {
    if(numbers[i] == numbers[i - 1]) {
        System.out.println("Duplicate: " + numbers[i]);
    }
}

This sorts the array numerically, then begins iterating the array. It checks the previous element in the array and if it equals the current element, then you have a duplicate.

share|improve this answer
3  
Best readable. A small suggestion: Add a while(i < numbers.length && numbers[i] == numbers[i - 1]) ++i; behind the if statement in the loop to prevent multiple output (according to original behavior) – tb- Nov 23 '12 at 17:48
Thank you all for answering! I'm very new to programming, so I haven't learned such functions as sort yet, so I see now that there are much easier ways of doing it. I tried this code and it works, however if there are more than two numbers in the array that are similar, it will print that number n-2 times times the number of repetitions within the array. I didn't manage to incorporate the small suggestion below. – Hatori Sanso Nov 24 '12 at 0:39
This isn't the most optimal, but it's fast enough. Also, there should probably be a check for multiple duplicates. I would expect [1, 1, 1, 2, 3] to only output "Duplicate: 1". This is trivial to implement: if (numbers[i] == numbers[i - 1] && numbers[i] != lastDup). – tjameson Nov 24 '12 at 8:42

Create a Map<Integer, Integer> (first number is the number you are looking, second is the number of appearences).

Run through your array. Each time you find a number, do map.get(numberFound) to see if you had already found it. If you had not, put the number with a counter of 1. If you had, retrieve the counter, increase it and put it back into the map.

share|improve this answer

I'm gonna throw my 2 cents in aswell :)

If you're allowed to used objects I'd do it like this.

Sets automatically holds non-duplicates so if it contains it it's no chance of the value going in a again.

int[] arrayOfInt = { 1, 2, 3, 5, 1, 2, 7, 8, 9, 10 };
Set<Integer> notDupes = new HashSet<Integer>();
Set<Integer> duplicates = new HashSet<Integer>();
for (int i = 0; i < arrayOfInt.length; i++) {
    if (!notDupes.contains(arrayOfInt[i])) {
        notDupes .add(arrayOfInt[i]);
        continue;
    }
    duplicates.add(arrayOfInt[i]);
}
System.out.println("num of dups:" + duplicates.size());
System.out.println("num of norls:" + notDupes.size());
share|improve this answer
1  
+1, but you don not know how duplicate you have for a number, so use Map<Integer,Integer> duplicates; = .. and int nbDuplicat = (int) duplicates.get(xNumber) and duplicates.put( nbDuplicat == 0 ? 1 : nbDuplicat++) - You can also if (!notDupes .add(arrayOfInt[i]);) { continue; } duplicates.add(arrayOfInt[i]); becaus it it cannot add it, it return false – cl-r Nov 23 '12 at 16:20
That was not apart of the question, though. – limelights Nov 23 '12 at 16:50
you are right! but my experience in true life have guessed than it will be asked soon, – cl-r Nov 24 '12 at 16:43

I would use Set for this example.Logic would be:

1) Create an empty Set MySet, and another empty Set ResultSet

2) Read each number and perform this on it:

a) Check if it is in MySet.
b) If its in MySet then put it in ResultSet.
c) If its not in MySet, then put it in Myset.

3) ResultSet contains the required numbers.

The benefit of this approach would be that the complexity would reduce to "n logn" instead of "n^2".

share|improve this answer
1  
I'd rather just use one set or array as I like to make programs that use as little memory as possible, but I will try this for fun! – Hatori Sanso Nov 24 '12 at 0:41
The space complexity is still N :D – Jagdeep Sidhu Nov 24 '12 at 1:17
@HatoriSanso "I'd rather just use one set or array as I like to make programs that use as little memory as possible" Please be careful about Premature Optimiation! It is good that you are trying to be efficient but realize that 'efficient' in computer terms could mean many things (memory is just the tip of the iceberg). When in doubt: 1. Make it work 2. Make it right 3. Make it fast (aka optimize) -Kent Beck – Tony R Nov 25 '12 at 4:39
and just to add my 2 cents, if you want to optimise, always calculate the space and time complexity, not just how many copies it uses. In my solution, two copies will be used for n elements( 2n ), and in your solution 1 copy will used (1n) , but the space complexity is same N , so it wont matter much. It is only a issue when you increase the complexity to NlogN or N^2. Also your solution has time complexity of N^2, and the one I wrote has worst case NlogN , so it is more efficient. Two copies of data dont affect space complexity/efficiency. – Jagdeep Sidhu Nov 25 '12 at 5:12

you may use google collection framework Guava's Multiset<Integer> to find repetating number.

Elements of a multiset that are equal to one another (see "Note on element equivalence", below) are referred to as occurrences of the same single element. The total number of occurrences of an element in a multiset is called the count of that element (the terms "frequency" and "multiplicity" are equivalent, but not used in this API). Since the count of an element is represented as an int, a multiset may never contain more than Integer.MAX_VALUE occurrences of any one element.

Multiset<Integer> set = HashMultiset.create();
void sjekk(){
        System.out.println("Write five numbers");
        for(int i = 0; i < numbers.length; i++){
        set.add(inn.nextInt());
    }
...
for(Multiset.Entry<Integer> entry : set.entrySet()){ 
 System.out.println("Element :-> "+entry.getElement()+" Repeat Cnt :-> "+entry.getCount());
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.