Fulvio Denza
Fulvio Denza

Reputation: 67

Delete duplicate in an array and insert first occurrence in a new array in C

I have to do a function which, taken as parameters a pointer (int *vect) and the dimension (dim) of the array allocated, returns a new array which contains all the elements of the old array not repeated and all the first occurrence of repeated elements, this is the code where i put the elements not repeated of the first array, but i don't know how to proceed to put the first occurrence of repeated elements (e.g. INPUT : vect={1;2;3;3;4;5;5} OUTPUT : {1;2;3;4;5})

int* deleteDup(int *vect,int dim){
    int* vect2,int dim2;
    vect2=malloc(sizeof(int)*dim2);
    int i,j,temp;
    int count=0;
    for(i=0;i<dim-1;i++){
        temp=vect[i];
        for(j=i+1;j<dim;j++){
            if(temp==vect[j]){
            count++;
        }
    }
    if(count==0){
        dim2++;
        vect2=realloc(vect2,dim2*sizeof(int));
        vect2[dim2]=temp;
    }
    *dim_nodup=dim2;
    return vect2;
}

Upvotes: 0

Views: 97

Answers (1)

This looks like homework to me.

You need to first count the number of unique elements, then allocate an array of that size, and then move one instance of each unique element to the new array.

This can be optimised various ways.

I prefer not to give you code or even pseudo code, as you should figure this out yourself when solving the problem.

i don't know how to proceed to put the first occurrence of repeated elements

To do this you must move elements one by one into the array you are returning, and for each item check if it is already in the array.

Good luck! :)

Upvotes: 1

Related Questions