Vector Union in C

Asked

Viewed 2,656 times

1

good evening. I am with an evaluative activity of the college to be delivered but I can not think of logic and solve the first activity. Can someone explain to me where is my mistake and a piece of advice to better understand indexes in for. I make a huge 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 enters [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...

1 answer

1


The problem is that your union finding code is not correct, both in terms of logic and implementation. Actually doing a loop/loop of 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 one has only 10 elements, which alone is incorrect and can give you a Segmentation fault. Also you are not using the vetb, as well as not removing repetitions but only rewriting values.

I propose you do so before:

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 I only used the vetu that it was the vector that had all the elements, and I removed the repeats of itself by adjusting the size and pulling elements.

In the end it was in tamanho2 the number of elements without repetitions of the array, which should be used next for writing to the console.

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

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

Other alternatives

It could have followed other solutions that guarantee better time complexity, but they are already much more elaborate and probably do not meet the solutions that await the exercise. I tried to use the one that looked more like the one I was using.

Example of alternative solutions with better complexities:

  • Use a hash table (hash table) and make an insertion of the elements in this table which will avoid repetitions and give a solution in the order of O(n). It will complicate if you need a script in the same order they were inserted.
  • Sort the resulting array with an efficient type method Quicksort or Mergesort who assures you O(nlogn) and then remove the repetitions that will be O(n²) or O(n) if you pass the non-repeated ones to a new array.
  • If you don’t need the resulting array (which was unclear in the question) you can follow another implementation excluding the vetu. This would go through A and show those that do not exist in B and vice versa, which gives it O(n²)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.