Union of Vectors in C

1

Good evening. I have an evaluative activity of the college to be delivered but I can not think of the logic and solve the first activity. Can anyone explain to me where my error is and advice to better understand indexes in for. I make a mess with them.

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


/*DECLARAÇÃO DE VARIAVEIS*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    setlocale(LC_ALL, "");
    int veta[10], vetb[10], vetu[20], vetd[10];
    int i, x, y, z, w, k;

    /*VETORES RECEBEM DADOS*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    printf("\n\t\t\tInsira os valores de VETOR A\n\n");


    for(i = 0; i < 10; i++) // Inserção dos valores ao vetor A
    {
        printf("Insira o valor do vetor A [%i]: ", i+1);
        scanf("%i", &veta[i]);

        vetu[i] = veta[i];      //ATRIBUI VALOR DO VETOR A AO VETOR C DIRETAMENTE.
    }

    printf("\n\t\t\tInsira os valores de VETOR B\n\n");


    for(i = 0; i < 10; i++) // Inserção dos valores ao vetor A
    {
        printf("Insira o valor do vetor A [%i]: ", i+1);
        scanf("%i", &vetb[i]);

        vetu[i+10] = vetb[i];   //ATRIBUI VALOR DO VETOR B AO VETOR C A PARTIR DA POSIÇÃO 10
    }


    /*VETOR B - RECEBE DADOS*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    printf("\n\t\t\tA União dos vetores A e B\n\n");

    for(x = 0; x < 20; x++)
    {
        for(y = 0; y < 20; y++)
        {
            if(vetu[y] == veta[x])
            {
                break;
            }
            else
            {
                vetu[y] = veta[x];
            }

        }
    }

    for(x = 0; x < 20; x++)
    {
        printf("%i\n", vetu[y]);
    }

}

The code should show me (All values contained in VECTOR A and VECTOR B without repetition. That is, if the user types [1] [2] [3] [3] [4] [5] E [6] [5] [3] [7] [8], the program should give me the following output: [1] [2] [3] [4] [5] [6] [7] [8].

But that's not what happens ...

    
asked by anonymous 27.09.2017 / 03:18

1 answer

1

The problem is that your code to find the union is not correct, both in terms of logic and implementation. Actually this is looping from 0 to 19 with x :

for(x = 0; x < 20; x++)

And then test vector A:

if(vetu[y] == veta[x])

When in fact this has only 10 elements, which in itself is incorrect and can give you a Segmentation fault . In addition, you are not using vetb , nor are you removing repetitions, but only rewriting values.

I propose that you do this first:

int tamanho2 = 20; //começa com o tamanho que definiu para a união

for(x = 0; x < 20; x++)
{
    //começa no numero seguinte ao x e vai apenas até ao tamanho2
    for(y = x + 1; y < tamanho2; y++) 
    {
        //se é um elemento repetido no vetu. Note que já não uso ==veta[x] neste if.
        if(vetu[y] == vetu[x]) 
        {
            //quando encontra vai até ao fim a puxar os elementos uma casa para trás
            //esta lógica acaba por remover o elemento repetido
            for (k = y; k < tamanho2-1; k++){
                vetu[k] = vetu[k+1];
            }

            //depois de ajustar os elementos "diminuir" o tamanho do array resultante
            tamanho2--; 
        }
    }
}

Example working on Ideone

Notice that I only used the% w / o of% that was the vector that had all the elements, and removed the repetitions of itself by adjusting the size and pulling elements.

At the end, the amount of elements without repetitions in the array was set to vetu , which is what you should use for writing to the console later.

Note : In the last part of the writing also has a small error that should correct:

for(x = 0; x < 20; x++)
{
    printf("%i\n", vetu[y]);
    //------------------^ tem de ser x e não y
}

Other alternatives

You could have followed other solutions that guarantee better time complexity, but are already much more elaborate and probably will not meet the solutions you expect for exercise. I tried to use the one closest to the one I was using.

Example of alternative solutions with better complexities:

  • Use a hash table and do an insertion of the elements in this table which will avoid repetitions and give a solution in the order of tamanho2 . It will complicate if you need to write in the same order they were inserted.
  • Sort the resulting array with an efficient QuickSort or MergeSort method that guarantees O(n) and then remove the reps that will be O(nlogn) or O(n²) pass the non-repeated to a new array.
  • If you do not need the resulting array (which was not clear in the question) you can follow another implementation by excluding O(n) . This would go through vetu and show the ones that do not exist in A and vice versa, which gives B
27.09.2017 / 12:52