How do I not print repeated numbers?

0

How do I not print repeated numbers? I saw some examples on the internet but they were something very complex in which I did not understand anything: x

#include <stdio.h>

int main (){
int vetA[10], vetB[10], vetC[20], i, j;

printf ("Informe 10 valores para o VETOR A:\n\n");
for (i=0; i<5; i++)
scanf ("%d", &vetA[i]);

printf ("\nInforme 10 valores para o VETOR B:\n\n");
for (i=0; i<5; i++)
scanf ("%d", &vetB[i]);

    for (i=0; i<5; i++)
    vetC[i] = vetA[i];

    for (i=5; i<10; i++)
    vetC[i] = vetB[i-5];

    printf ("\nA uniao dos vetores e:\n\n");
    for (i=0; i<10; i++)
    printf ("%d, ", vetC[i]);
}
    
asked by anonymous 22.10.2017 / 23:48

1 answer

2

You can solve the problem, only added to vetC whenever you know that the element does not already exist in vetC . To simplify, we can start by constructing a function that performs the verification:

int existe(int* vetor, int tamanho, int elemento){
    int i;
    for (i = 0; i < tamanho; ++i){
        if (vetor[i] == elemento) return 1;
    }

    return 0;
}

Notice two important details of this function:

  • The return type was marked with int when it is used as 1 or 0 , true or false. This is because in C we do not have natively booleans.
  • The size of the vector has to be passed as a parameter because there is no way to know it within the function.

Now in main we go through the two vectors vetA and vetB and only add if they do not already exist:

int tamC = 0;

for (i = 0; i < 5; ++i){
    //se vetA[i] ainda não existe em vetC adiciona a vetC e aumenta a quantidade
    if (!existe(vetC, tamC, vetA[i])) vetC[tamC++] = vetA[i];
    if (!existe(vetC, tamC, vetB[i])) vetC[tamC++] = vetB[i];
} 

Notice that only if it does not exist it is added in vetC and incremented the tamC variable. This means that at the end of for , tamC indicates the actual size of vetC taking into account duplicate elements that have not been inserted.

This solution adds elements of A and B interleaved. If you want to keep the original order, with all of A and then all of B, you have to separate by 2% with%:

for (i = 0; i < 5; ++i)
    if (!existe(vetC, tamC, vetA[i])) vetC[tamC++] = vetA[i];

for (i = 0; i < 5; ++i)
    if (!existe(vetC, tamC, vetB[i])) vetC[tamC++] = vetB[i];

If the size of the vectors is an initially defined constant then it is best to make this explicit with a for eg:

#define TAMANHO 5

View the program with these Ideone changes

Final note: This solution is quadratic (O (n²)) and therefore may not work if the input is gigantic. In this case you can opt for another more efficient solution, even if it involves pre-processing the input data.

    
23.10.2017 / 04:19