2
I created the following function to join two vectors (not being able to repeat an equal number), follows the function and the comments showing what I did and the error it is giving:
void uniao(int *A, int *B, int qnt)
{
int C[qnt*2], cont, cont2, pos = 0, dif = 0;
for(cont = 0; cont < qnt; cont ++)
{
C[cont] = 0; // zera o vetor do resultado
}
for(cont = 0; cont < qnt; cont ++)
{
for(cont2 = 0; cont2 < qnt; cont2 ++)
{ // compara cada numero do vetor A com todos os numeros do vetor B
if(A[cont] != B[cont2]) // se for diferente ele incrementa um contador
dif += 1;
}
if(dif == (qnt))
{ // se ele for único (diferente de todos os outros numeros do outro vetor
C[pos] = A[cont]; // ele armazena em um novo vetor
pos += 1; // muda a posição desse novo vetor
}
dif = 0; // redefine o contador
}
/*
aqui é a parte que não funcina, primeiro eu armazenei só os números que não
são repitidos do vetor A, agora para completar a união, basta adicionar ao vetor C
todos elementos do vetor B (cujo não serão repitidos), porém preciso adicionar esses
elementos nas posições posteriores do que li ali no for anterior, por isso a variavel pos
agora varro todos elementos do vetor após a última posição que adicionei e atribuo o valor de B a ela,
porem como o cont começa do pos, ele não vai pegar os 'pos' primeiros elementos do vetor B, como resolvo
isso? Tentei colocar outro for dentro dele mas não entendi muito bem
*/
for(cont = pos ; cont < qnt*2; cont ++ )
{
C[cont] = B[cont];
}
}
In this case it does not take x first positions of vector B because I equalized the cont to pos. A solution I thought would be to match it in the first for, all elements of c equal to null (but I don’t know how to do this) and then make an if to fill only the null elements, but how to null an int vector? Because 0 can give a wrong result, because the vector A or B can have a digit 0
It’s unclear what you need to do... The result vector cannot have any repeated number, or cannot repeat consecutive numbers ([1,2,3,2,1] is acceptable?). You’re comparing the elements of the same position in the input vectors, but it doesn’t seem to be what you wanted to do.
– RSinohara
The numbers just can’t be repeated, the order doesn’t matter, because then I’ll sort, what I want is the vector union, example, A= 1, 2, 4, 5, 8 and B= 1, 2, 3, 5, 9 the union would be A U B= 1, 2, 3, 4, 5, 8, 9, in which case the order was automatic because the vectors A and B were already ordered, but it’s simply taking all the numbers of the two vectors and playing on one vector and taking out the same numbers, only I did it backwards, first I took out the same numbers and then I was going to put the other elements..
– Leonardo
I managed to change a little by putting a conta2 in the last for and C[cont] = B[cont2]; after that I put conta2 += 1; hence the output was: C=8, 4, 5, 9, 3, 2, 1, 8, 2, 5.. In other words, he picked up garbage, because it was only to show up to 1
– Leonardo