Hi, I'm working on this for this last weekend and have been thinking for hours to figure out how the hell can I print the duplication in arrays that's been initialized with random numbers... :( does anyone have suggestion or ideas on how to do this? I'm just having problem with the printing part, because it's printing it twice, because:

EXAMPLE: 1 2 3 4 4 5 6 1 2

counter at a[0] and a[7] have the same value, and printing needs to be inside the for loops so that it can print for all numbers that have duplication... such as in this case "4" and "2" too! :(

I just need to make additional IF requirement so that it doesn't print twice, but I don't have idea on how can I specify IF THIS NUMBER has been PRINTED, do not print again... :-/ something like that... pliz help thx

Recommended Answers

All 5 Replies

Here's two ways to do it:
1) Before you print a value, iterate over the list from beginning to that value and check if it's a duplicate. If it is, skip it. This will make your print loop run in O(n^2) time worst case.
2) Create a hash table. Before printing something, check if it's in the hash table. If not, print it and add it to the table. This will make your print loop use up to double the memory, but on large data sets it will run faster than the first option.

Even easier...
Before you print anything, create a Map containing each distinct value in the array as the key and the number of occurances as the value.
After that, just iterate over those keys and extract their values for printing.
Worst case, that's equivalent to running over the array twice, best case it's equivalent to running over it once plus a single lookup.

Did the OP want to eliminate duplicates or summarize the number of times they occur? If the latter, jwentings solution is better (as in, mine don't keep counts :o)

Finish :)

I've been struggling to this for the whole day! :( HELPPPP!!!!

Expected output:

Number 2 has duplicate: 2 <-- the number
Number 3 has duplicate: 3

and so on...

OMGGGG!!! NEVERMINDDD I GOT IT, FRICKEN change the != to == on arrayCheck wth... -.-" THANX GUYS!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.