aspose file tools*
The moose likes Beginning Java and the fly likes Listing duplicate numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Listing duplicate numbers" Watch "Listing duplicate numbers" New topic
Author

Listing duplicate numbers

Grant Allen
Greenhorn

Joined: Jun 04, 2006
Posts: 8
okay i have an array of 100 elements, and write a method that lists all the duplicate numbers, how would i do this??
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
if the range of the numbers is not large, create an int array to the max number (+1)
then iterate your array, and each number becomes the element of the int[], where you ++

something along these lines

for(int x...)
{
intArray[numberArray[x]]++;
}

now you iterate the intArray and if any > 1, its a duplicate
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

I personnally don't like the array solution
"If the range of the numbers is not large" is a little bit too much demanding, isn't it ? Whati s there actually are big numbers in it ?

What about sorting the array first and checking for the same consecutive numbers ?


[My Blog]
All roads lead to JavaRanch
Grant Allen
Greenhorn

Joined: Jun 04, 2006
Posts: 8
My array contains 100 elements range 100 + 100
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Michael has a good solution.
[ June 04, 2006: Message edited by: wise owen ]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Michael has a good solution.

Why do you consider this to be a good solution ?
A solution which works for small numbers only is not a good solution to me. If it is for Grant, then fair enough.
[ June 04, 2006: Message edited by: Satou kurinosuke ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Indeed, the array solution is a limited one. One general solution would involve a java.util.Set or java.util.Map object, depending on how you interpret the phrase "list the duplicate numbers."

Note, folks, that this is clearly a homework problem; let's not hand out the solution on a silver platter.


[Jess in Action][AskingGoodQuestions]
 
 
subject: Listing duplicate numbers