Vector union

Asked

Viewed 559 times

-2

How do I join 2 vectors into 1 single vector ? Without repeating the numbers ?

Question: Make a program that reads two vectors of 10 elements. Create a vector that is the union between the two previous vectors, that is, that contains the numbers of the two vectors. It should not contain repeated numbers.

@Dit: I saw some examples on the Internet and I came to that but to ta well wrong ;-;

#include <stdio.h>

int main (){
int vetA[2], vetB[2], vetC[4], i,l,j;


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

printf ("Informe 10 valores para o VETOR B:\n");
for (i=0; i<2; i++){
    scanf ("%d", &vetB);
}

printf ("\nA uniao e: ");
for (i=0; i<2; i++){
    if ((vetC[0] != vetA[i]) && (vetC[1] != vetA[i]) && (vetC[2] != vetA[i]))
    printf ("%d ", vetA[i]);
}

for (i=0; i<l; i++){
    printf ("%d ",vetC);
}
for (j=0; j<2; j++){
    if ((vetC[0] != vetB[i]) && (vetC[1] != vetB[i]) && (vetC[2] != vetB[i]))
    printf ("%d ", vetB[i]);
}
}

1 answer

3


The vetC could begin as having all the elements of the vetA and having 20 elements.

Then put a for within the other to choose which elements of the vetB you put in the vetC. The for external runs through the vetB and the intern goes through the vetA.

Place a variable inside the for external call achou and initialize it with 0. If in the for internal you discover that the element of vetB (of for external) is equal to the element of the vetA (of for internal), you exchange the value of achou to 1. Use a if to make that check.

After the for internal, still within the for external, use another if with the found variable to decide if you put the vetB in the vetC.

You’ll also need a variable to track how many elements you’ve put into vetC, since the size of the vetC is variable depending on the number of repetitions.

  • thank you :D vlw man

  • This algorithm works well sss vetA contain no repetitions. vetB can be a hassle-free bag that this algorithm keeps working.

Browser other questions tagged

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