• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Calculating number of unique values in an integer array - any help

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a simple array with ten integer values. I can get the 'for' loop to count the total number of values in the array, the maximum etc, but how do I get it to calculate the total number of unique/distinct values in the array.

My current code is as follows,



This code calculates the maximum value in the array. Any idea how to change this?

Any help really appreciated!
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One simple way to get the total number of unique values is to place them all on a HashMap, using the value itself as the key, and then the number of unique values is the size of the HashMap.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the same path, but with little difference, when u add a member from the Array to your hasmap u can verify with containsKey() method of HashMap. If u get true then move on to Next element in Array, other wise add a member from array to HashMap.

At the end HashMap.size() and u can find the total number of unique member in your array.

This way it mightget improve the performance
 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks for the replies. Have a great week.
 
Time flies like an arrow. Fruit flies like a banana. Steve flies like a tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic