0

How can I eliminate the elements that are the same in an array?

For example I have the array a[ 1 2 2 3 6 5 5 8] I tried to put them in order and than I did this to eliminate the same elements: for(i=1;i<=n;i++){ if(a[i]==a[i+1]){ a[i]=a[n]; n--; } } In which "n" is the limit of the array. I apreciate the help:) ps:I'm a first year student, so don't take me very hard :)

25th Nov 2016, 6:23 PM
Hipnotic C
Hipnotic C - avatar
1 Answer
0
First, and you should know it already : in all languages (except Lua, and maybe some other exotic ones), you start indexes at 0! Not 1! Then, you have to delete these elements, you are just doing nothing in this code. One solution that comes to my mind just now is : put the unique elements in an other array and for each element of the original array, check if it is already in the new array. Not at all efficient, but you could do that. Or, (maybe, I would do that in Python), use a set (and put it back in an array if you need to). Not much more efficient, but easier to debug if you know how to use sets... Sorry about the little rant earlier, it just bugs me out that anyone (even first year students) doesn't understand Arrays 101 : start at 0. Of course all languages have different kinds of arrays, but they (nearly) all start at 0. Hope that helped.
25th Nov 2016, 6:46 PM
Amaras A
Amaras A - avatar