# Thread: May I know the algorithm to calculate how many different values are in the array?

1. ## May I know the algorithm to calculate how many different values are in the array?

May I know the algorithm to calculate how many different values are in the array?

Input array:{ac,a,b,a,a,ac,b,b,a,a}

Output:Ac=2,a=5,b=3
Total number of different values=3

Thanking you,
With Regards,
Nandhini  Reply With Quote

2. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: May I know the algorithm to calculate how many different values are in the array?

To calculate how many distinct elements are in an array put the array elements into an instance of Set and look at its size. See the example in the The Set Interface page of Oracle's Tutorial.

To find out both the distinct elements *and* their frequencies you could use a Map which links each distinct element (as key) with its frequency (as value). For each element of the array you add an entry to the map or update an existing one: if the element is there already you increment the count, if not you create a new entry with a count of 1. Again, there is an example in the Tutorial's Collection on the page The Map Interface.  Reply With Quote

3. ## Re: May I know the algorithm to calculate how many different values are in the array?

Thank you   Reply With Quote

4. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: May I know the algorithm to calculate how many different values are in the array?

You're welcome  Reply With Quote

5. ## Map Interface- doubt

input
policy1= {N, Y, Y, Y, N, Y, N, NULL, Y,N}
Java Code:
```Map<String, Integer> m = new HashMap<String, Integer>();
for(j=0;j<=9;j++) {
Integer freq = m.get(policy1[j]);
m.put(policy1[j], (freq == null) ? 1 : freq + 1);
}
System.out.println(m.keySet());
System.out.println(m.values());
System.out.println(m.entrySet());
System.out.println(m.size() + " distinct words:");
System.out.println(m);```
I got the following output
3 distinct words:
[null, N , Y ]
[1, 4, 5]
[null=1, N =4, Y =5]
3 distinct words:
{null=1, N =4, Y =5}

Further I want to assign
A1=null, A2=N, A3=Y
A1size=1, A2size=3, A3size=6
Highest value=A3
for(j=0;j<=9;j++){
If(policy1[j]==null)
If(A2>A3)
policy1[j]=A2;
else
policy1[j]=A3;

I Dont know how can I utilize m values.{null=1, N =3, Y =6}

Thanking You,
With Regards,
Nandhini.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•