This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Comparing Integers in Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing Integers in Array" Watch "Comparing Integers in Array" New topic
Author

Comparing Integers in Array

Sam Benry
Ranch Hand

Joined: Mar 21, 2008
Posts: 89
lets say we have
int[] c = new int[5];

this is later filled with 5 different values from 2 to 14 (repetition is allowed)

I need a way to find out how many numbers are repeated and how many times this number is repeated.

lets say the array was { 3 , 12 , 3 , 3 , 12 }
3 is repeated 3 times
12 is repeated 2 times

what is a good method for doing this?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11169
    
  16

'good' depends on many things... how big will the real array be? what is the range of the expected values?

one way might be a map that uses the value as the key. each time you read a value, like '3', you check to see if that key/value is defined. if so, you increment the value. If not, you create it with a value of 1.

when you're done, you get a list of all the keys, and use that to get the counts.

if your range is sufficiently small, you could just define an int array of say (from your example) 15. Then, as you read each value, increment the int at that index by 1.

'good' is a balance between speed, readability, maintainability, and ease of programming.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Guido Sautter
Ranch Hand

Joined: Dec 22, 2004
Posts: 142
this sounds like a programming exercise ... hints:

The trivial solution uses two nested for loops and runs in o(n�) - avoiding dupliacte output will take an additional data structure, eg a second array or a set.

The half-trivial solution involves sorting and runs in o(n*log(n)).

The nifty solution involves a HashMap and runs in linear time.
 
 
subject: Comparing Integers in Array
 
Similar Threads
Finding top 3 repeated numbers in an array
To "RMNWSC" or not to "RMNWSC"
how many objects are create??
K&B , Chap1 Q11
Need help on painting using JNI.