Ad

Printing Unique Values Of The Array In C

- 1 answer

I wrote a function creating a dynamic array of random values and another function creating a new array consisting of unique values of the previous array. The algorithm used counts unique values correctly. However, I faced a problem in printing all values. In the example below the program printed 7 2 12714320 4 5 instead of 7 2 4 5 6 .

This is the program which can be tested:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *delduplicate(int *v, int size_old, int *size_new);

main()
{
    int n;
    int *norepeat;
    float *results;
    int dim, size_norepeat, i;
    
    int a[7] = {7,2,2,4,5,6,7};
    
    norepeat = delduplicate(a, 7, &size_norepeat);
    
    for (int i = 0; i < size_norepeat; i++)
        printf("%d ", norepeat[i]);
}



// delduplicate function
int *delduplicate(int *v, int size_old, int *size_new)
{
    int i, j, k = 1, uniques = 1, repeats, *new_v, temp;
    
    // count the number of unique elements
    for (i = 1; i < size_old; i++)
    {
        int is_unique = 1;
        
        for (j = 0; is_unique && j < i; j++)
        {
            if (v[i] == v[j])
                is_unique = 0;          
        }
        
        if (is_unique)
            uniques++;
    }
    
    *size_new = uniques;
    
    // create new array of unique elements
    new_v = (int*) malloc(*size_new * sizeof(int));
    
    // fill new array with unique elements
    new_v[0] = v[0];
    
    for (i = 1; i < size_old; i++)
    {
        int is_unique = 1;
            
        for (j = 0; j < i; j++)
        {
            if (v[i] == v[j])
                is_unique = 0;
        }
    
        if (is_unique)
            new_v[k] = v[i];
            k++;
            
    }
    return new_v;
}

The problem should be happening here:

// fill new array with unique elements
new_v[0] = v[0];

for (i = 1; i < size_old; i++)
{
    int is_unique = 1;
        
    for (j = 0; j < i; j++)
    {
        if (v[i] == v[j])
            is_unique = 0;
    }

    if (is_unique)
        new_v[k] = v[i];
        k++;       
}
Ad

Answer

Your problem is probably occurring in the following section -

if (is_unique)
    new_v[k] = v[i];
    k++;

Here you are incrementing k at each iteration. However, you only want to increment it whenever you have found a unique element. if() without brackets only considers the first statement. So change it to this -

if (is_unique){
    new_v[k] = v[i];
    k++;
}

This change should make your program run fine.


Side Note : If you do not want to use brackets for an if() , for() , etc, you can separate the statements by commas and use without having the brackets. Like this -

if (is_unique)
    new_v[k] = v[i],
    k++;
Ad
source: stackoverflow.com
Ad