Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,I have problem with counting unique numbers in array.I have tried one code but it has problem.

What I have tried:

Here is my code:
Java
package dan1;
 
import java.util.Scanner;
 
public class Nizovi7 {
    public static void main(String [] args){
        Scanner scanner = new Scanner(System.in);
        int counter = 0;
        int n = scanner.nextInt();
        int [] niz = new int [n];
        for(int i = 0;i < n;i++){
        	niz[i] = scanner.nextInt();
        }
        for(int i = 0;i<n;i++){
        	for(int j =0;j<n;j++){
        		if(niz[i]==niz[j]){
        			continue;
        		}
        		else{
        			counter++;
        		}
        	}
        }
        System.out.println(counter);
    }
}

Where is problem?
Posted
Updated 25-Jan-18 2:19am

I'm not a Java programmer but if you sort the array first in ascending or descending order, then testing for and counting unique numbers is very easy.

Here is a C# solution:
C#
int[] numbers = new int[] { 1, 5, 2, 9, 4, 7, 1, 5, 1, 9 };
Array.Sort(numbers);

int uniqueCount = 0, current = 0;
bool isRepeat = false;
foreach (var number in numbers)
{
    if (number != current)
    {
        if (current != 0 && !isRepeat)
            uniqueCount++;
        current = number;
        isRepeat = false;
    }
    else
    {
        isRepeat = true;
    }
}
 
Share this answer
 
v2
Comments
Member 13430000 26-Sep-17 4:33am    
Well i think it is good but i need solution in java cuz i dont know c# and dont know how to transfer this if statement
if (number != current)
{
if (current != 0 && !isRepeat)
uniqueCount++;
current = number;
isRepeat = false;
}
Graeme_Grant 26-Sep-17 5:46am    
From what I can read, it works the same: if else statement in java[^]
A suggestion: if you sort the array, then identical numbers are next to each other, and a lot easier to count...

And Java has a built-in Arrays.Sort method: Arrays.sort() in Java with examples - GeeksforGeeks[^]
 
Share this answer
 
Comments
Graeme_Grant 26-Sep-17 3:37am    
deja vu? ;)
OriginalGriff 26-Sep-17 5:56am    
I didn't see your solution while I was typing mine: the cat brought in a mouse halfway through, and Herself refuses to deal with them...
[no name] 26-Sep-17 4:33am    
Really Worthy Answer Griff Sir..
Use an the HashSet<Integer> class: it provides automatic uniqueness:
Java
import java.util.HashSet;

public class Uniq
{
  public static void main(String [] args)
  {
    int ar[] = {1, 12, 53, 12, 24, 36, 17, 89, 12};

    HashSet<Integer> hs = new HashSet<Integer>();
    for (int i : ar)
    {
      hs.add(new Integer(i));
    }
    System.out.println(hs.size());
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900