# Removing Duplicate Values From an Array

• November 30th, 2011, 05:25 PM
nicsa
Removing Duplicate Values From an Array
I am to remove all duplicates form an array.

For example:
4 7 11 4 9 5 11 7 3 5
should be changed to
4 7 11 9 4 3

I am not supposed to use hashtables. Is there a simple way to do this. I am trying to do it with multiple for loops.

• November 30th, 2011, 05:42 PM
Junky
Re: Removing Duplicate Values From an Array
The simplest way would be to use Sets but I assume you are not allowed to use them either.

You could create a 3rd array and only add a value to it if it is not present in either of the first 2 arrays. Or you would need to loop over the smaller array and for each value loop over the larger array. When you find a match, move all values down one spot. This has 2 problems to overcome:

You will still have values left at the end of the array eg after "removing" the first 4 the array would be 7 11 4 9 5 11 7 3 5 5, then after the next 4 it would be 7 11 9 5 11 7 3 5 5 5.

The other problem would be if you had the same value next to each other: 4 4 3 5 1 7. If you are not careful then removing the first 4 gives 4 3 5 1 7 7. Then you continue on searching at the second element and leave the other 4 at the start of the array.
• November 30th, 2011, 06:31 PM
Norm
Re: Removing Duplicate Values From an Array
Another idea. Use a contains() type method.
Copy the first number to the new array.
Then in a loop
get the next number from the old array
does the new array contain this number
end loop
• November 30th, 2011, 06:37 PM
Junky
Re: Removing Duplicate Values From an Array
Yeah that is what I meant by my first suggestion but I didn't word it very well. Thanks for the clarification Norm.
• November 30th, 2011, 06:40 PM
Norm
Re: Removing Duplicate Values From an Array
I left out the problem of array sizes.
• November 30th, 2011, 06:53 PM
Junky
Re: Removing Duplicate Values From an Array
That is why working with Collections is by far the better option. But when you are a poor 1st year student you get stuck with silly assignments doing a kludge with an array.
• November 30th, 2011, 06:55 PM
Norm
Re: Removing Duplicate Values From an Array
I programmed assembly all my life. Arrays are much better.