Remove element from a Vector in "C"

Asked

Viewed 1,061 times

0

I must fill two vectors, A and B, with 10 elements each, then do the Interseccao and the Union, in the union, I must remove the repeated elements.

At the time, the intersection was made, within the intersection of the I placed in another vector (vector[c]) the indices of the elements that are in B and A

In the union, first do one for and add all the elements of vector A, in the first 10 positions of another vector (vectorU[]);

However, with difficulty in solving the passage of the elements from vector B to vector U, removing the indices containing the repeated elements between vector A and vector B; follows the code:

#include <stdlib.h>  
#include <time.h> 


int Conjuntos()
{

int vetorA[10];
int vetorB[20];

int *vetorR;

int *vetorU;
int *vetorIn;
int *vetorDif;


int tamVetor = 0;
int tamVetorU = 0;

vetorIn = malloc(sizeof(int*)*tamVetor);

vetorDif = malloc(sizeof(int*)*tamVetor);

vetorU = malloc(sizeof(int*)*tamVetorU);


vetorR = malloc(sizeof(int*)*tamVetor);


srand(time(NULL));// inicia a funcao rand semente;

for (int i = 0; i < 10; i++)
{
    vetorA[i] =  rand() % 100;


}


for (int i = 10; i < 20; i++)
{

    vetorB[i] =  30 + ( rand() % 70 );

}
///
    printf("Elementos de A:{ ");
for (int i = 0; i < 10; i++)
{

    printf("%d, ",vetorA[i]);
}
printf("}\n");

// imprimi vetor b

    printf("Elementos de B:{ ");
for (int i = 10; i < 20; i++)
{

    printf("%d, ",vetorB[i]);
}
printf("}\n");

//verifica quais numeros sao repetidos
int c = 0;
for(int i = 0; i < 10; i++)

{
    for (int a = 10; a < 20; a++)
    {

    if (vetorA[i] == vetorB[a])
    {

    tamVetor++;

    vetorIn[c] = vetorA[i];
    vetorR[c] = a; //guarda os indices dos elementos do vetorB que tambem estao no vetorA
    c++;





vetorIn = realloc(vetorIn,sizeof(int)*tamVetor);

vetorR = realloc(vetorR
,sizeof(int)*tamVetor);

if (vetorIn==NULL)
{
printf("Memoria insuficiente.\n");
exit(1); /* aborta o programa e retorna 1 para o sist. operacional */
}


if (vetorR==NULL)
{
printf("Memoria insuficiente.\n");
exit(1); /* aborta o programa e retorna 1 para o sist. operacional */
}




    }//fecha o if



    }// fecha for de dentro
    }//fecha o for de fora

    printf(" tamanho do vetor e: %d\n", tamVetor);

    printf("Os elementos da Intersecao entre A e B sao: { ");

    for(int i = 0; i < tamVetor; i++)
    {
        printf("%d, ", vetorIn[i]);

    }

    printf("}\n");

///  adiciona os elementos de a em umiao    

for (int i= 0; i < 10; i++)
{


        tamVetorU++;


    vetorU = realloc(vetorU,sizeof(int*)*tamVetorU);



if (vetorU==NULL)
{
printf("Memoria insuficiente.\n");
exit(1); /* aborta o programa e retorna 1 para o sist. operacional */
}

vetorU[i] = vetorA[i];
    }


printf(" indices do vetor b q possuem numeros iguais ao vetor a\n");
for (int i = 0; i < tamVetor; i++)
{
printf("%d \n", vetorR[i]);
}




//adiciona os elementos de b a unao

/*Aqui esta o que nao consiguo resolver, neste for, adiciono os elementos do vetorB ao vetorU, porem preciso retirar os elementos repetipos, que estao no vetor[R], em alguns teste, consegui, porem na posicao do elemento repetido ficava o "0" e o ultimo elemento do vetor nao entrava no vetor[i]
*/


for(int i = 10; i < 20; i++)

{
    for(int c = 0; c < tamVetor; c++)
    {

    if (i == vetorR[c])
    {






    }
    else
   {
    tamVetorU++;


    vetorU = realloc(vetorU,sizeof(int*)*tamVetorU);



if (vetorU==NULL)
{
printf("Memoria insuficiente.\n");
exit(1); 
}





vetorU[i]= vetorB[i];


   }
    }
}










//int n = 20 - tamVetor;

printf ("Os elementos da uniao entre A e B sao: { ");
for (int i = 0; i < tamVetorU; i++)
{

printf(" %d, ", vetorU[i]);
    }



printf("}\n");


}












int main()
{

    Conjuntos();

    return 0;
}

// after the editions

   for(int i=10; i<20; i++) //Coloca -1 nos repetidos de B
   for(int c=0; c<tamVetor; c++){
   if (vetorB[i] == vetorIn[c])
   {
   vetorB[i] = -1;
   }
   }

   printf("os elementos de b agr sao: ");

   for (int i = 10; i < 20; i++)
     {
    printf("%d,",vetorB[i]);

   }

   printf("}\n");


    int k = 10;
   int tamVetorU = 20 - tamVetor;
   vetorU = realloc(vetorU,sizeof(int*)*tamVetorU);

    printf("o tamanho do vetor u e: %d\n", tamVetorU);

   for(int i=0; i<tamVetorU;i++){ //Preenche vetorU
   if (i<10){
   vetorU[i] = vetorA[i];

   }
    else
   {
  if (vetorB[k] != -1) 
  {
  vetorU[i] = vetorB[k];

}
k++;

}
 }

2 answers

1

I haven’t seen your whole code, but the simplest solution that came to mind is:

Since you already have the elements that are both in A and B, do a "scan" (inside another for) by placing in vector B in place of the elements that are repeated a key value like "-1", and in when passing vc only transfers from B to vector[] items other than "-1" if(vetorB[i] != -1).

int aux = 30 - tamVetor; //identifica o tamanho de vetorU
int k=0; //variavel auxiliar
vetorU = malloc(sizeof(int)*aux); //dinamicamente vetorU
for(int i=0; i<20; i++) //Coloca -1 nos repetidos de B
  for(int y=0; y<tamVetor; y++){
    if(vetorB[i] == vetorIn[y])
      vetorB[i] = -1;
  }

for(int i=0; i<aux; i++){ //Preenche vetorU
  if(i<10)
    vetorU[i] = vetorA[i];
  else{
    if(vetorB[k] != -1)
      vetorU[i] = vetorB[k];
    k++;
  }
}

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


int Conjuntos()
{

  int vetorA[10];
  int vetorB[10];
  int tamVetor = 0;
  int tamVetorU = 0;
  int *vetorR;
  int *vetorU;
  int *vetorIn = malloc(sizeof(int)*tamVetor);
  int *vetorDif;
  int k = 0;
  int i;
  srand(time(NULL));// inicia a funcao rand semente;

  for (int i = 0; i < 10; i++)
      vetorA[i] =  rand() % 100;

  for (int i = 0; i < 10; i++)
      vetorB[i] =  30 + ( rand() % 70 );

  printf("Elementos de A:{ ");

  for (int i = 0; i < 10; i++)
      printf("%d, ",vetorA[i]);

  printf("}\n");

  // imprimi vetor b

  printf("Elementos de B:{ ");
  for (int i = 0; i < 10; i++)
      printf("%d, ",vetorB[i]);

  printf("}\n");

  //verifica quais numeros sao repetidos

  int j = 0;
  for(int i = 0; i < 10; i++)
      for (int j = 0; j < 10; j++)
        if (vetorA[i] == vetorB[j])
        {
          tamVetor++;
          vetorIn[k] = vetorA[i];
          vetorIn = realloc(vetorIn,sizeof(int)*tamVetor);
          k++;
        }

  printf("Os elementos da Intersecao entre A e B sao: { ");
  for(int i = 0; i < tamVetor; i++)
    printf("%d, ", vetorIn[i]);

  printf("}\n");

  int aux = 20 - tamVetor; //identifica o tamanho de vetorU
  k=0; //variavel auxiliar
  vetorU = malloc(sizeof(int)*aux); //dinamicamente vetorU
  for(i=0; i<10; i++) //Coloca -1 nos repetidos de B
    for(j=0; j<tamVetor; j++){
      if(vetorB[i] == vetorIn[j])
        vetorB[i] = -1;
    }

  for(i=0; i<aux; i++){ //Preenche vetorU
    if(i<10)
      vetorU[i] = vetorA[i];
    else{
      if(vetorB[k] != -1)
        vetorU[i] = vetorB[k];
      k++;
    }
  }

  printf ("Os elementos da uniao entre A e B sao: { ");
  for (int i = 0; i < aux; i++)
    printf("%d, ", vetorU[i]);
  printf("}\n");

}

int main()
{

    Conjuntos();

    return 0;
}

inserir a descrição da imagem aqui

  • Thank you for contacting Leonardo! Could you explain to me how to do this, I did not understand well!

  • I edited the comment with the code snippet.

  • Leonardo, okay, I figured out what to do, so I took your concept and used it in my code. was thus, with the elements of the intersection of A and B in the vector In, I made a for that compared the elements of B, with the intersection, building a new vector B , that having the element in common with A, receives -1 in its place:

  • then add the elements of A in vector U, until Indice 10 has all the elements of A, and from Indice 11, receive the elements of vector B , if these are different from -1

  • However, the output from the elements of the U which are only vectorB, are clear with strange values , I do not understand the pq, I will put these passages of code in the question

  • From what I understand from your code, A is size 10 and B is size 20. When Voce will do tamVetorU, you are doing " 20 - tamVet" and that gives less positions than the 20 you use in "for (int i = 0; i < 20; i++)"

  • 'int aux = 30 - tamVetor; //identifies the vector sizeU' This line of mine, the 30 is the sum of the size of the 2 if we were only going to merge, without removing the intersected elements. How we remove the intersected elements I do the "- tamVetor".

  • Actually, and because I did so, for vector A[] indices go from 0 to 10, and pro vector B[] indices go from 10 to 20, I made the corrections and however I returned to zero, the elements -1 in vector B are not passed to vector U, beauty, but ae in place of them is placed 0, I’ll put the code again in the question so you can take a look, I’m grateful for the help!

  • I don’t see why they are inserting 0, it must be some pointer error. You are required to use realloc in the project?

  • Leonardo, can you test the code now? If yes, I did the editing again, I put malloc only once after receiving the value to the size that will be the vector joined(tamVetorU = 20 - tamVetor), however the results are the same, 0 instead of -1, because sera?

  • I took your code and tidied it up, added my answer. There’s some mistake of it, for something I forgot to change, but that’s pretty much it.

  • Leonardo, I tested the code here, but the output is now all messed up, I’m using android to write the codes, in the app c4droid, maybe it’s a problem in the compiler, when I have access to a computer I test to see! However in my code the only error and in the place of the -1 appear a 0, da para resolver la no printf, putting a condition that if the value was == -1 it would not print, it would be a way to solve, but anyway the vector would have an element 0, that would be wrong, anyway, thanks for the help here, it was of great value!

Show 7 more comments

1

If you already "know" the size of the vectors, I don’t see the need to implement an algorithm using dynamic allocation.

Follows a program (tested) capable of solving your problem using a specific function for each operation:

#include <stdio.h>

void interseccao( int saida[], int * stam, int v1[], int v1tam, int v2[], int v2tam )
{
    int i = 0;
    int j = 0;

    *stam = 0;

    while( (i < v1tam) && (j < v2tam) )
    {
        if( v1[i] < v2[j] )
        {
            i++;
        }
        else if( v2[j] < v1[i] )
        {
            j++;
        }
        else if( v1[i] == v2[j] )
        {
            *saida++ = v2[ j++ ];
            (*stam)++;
            i++;
        }
    }
}


void uniao( int saida[], int * stam, int v1[], int v1tam, int v2[], int v2tam )
{
    int i = 0;
    int j = 0;
    int k = 0;

    *stam = v1tam + v2tam;

    for( i = 0; i < v1tam; i++ )
        saida[j++] = v1[i];

    for( i = 0; i < v2tam; i++ )
        saida[j++] = v2[i];

    for( i = 0; i < *stam; i++ )
    {
        for( j = i + 1; j < *stam; j++ )
        {
            if( saida[i] == saida[j] )
            {
                for( k = j; k < *stam; k++ )
                    saida[ k ] = saida[ k + 1 ];

                (*stam)--;
                j--;
            }
        }
    }
}


void exibir_vetor( char * desc, const int v[], int tam )
{
    int i = 0;

    printf("%s", desc );

    for( i = 0; i < tam; i++ )
        printf(" %d", v[i] );

    printf("\n");
}


int main( void )
{
    int A[ 10 ] = { 1, 2, 5, 7, 9, 10, 11, 13, 14, 19 };
    int B[ 10 ] = { 1, 3, 5, 7, 8, 10, 11, 12, 14, 16 };

    int saida[ 20 ];
    int n = 0;

    exibir_vetor( "Vetor A:", A, 10 );
    exibir_vetor( "Vetor B:", B, 10 );

    interseccao( saida, &n, A, 10, B, 10 );
    exibir_vetor( "Interseccao:", saida, n );

    uniao( saida, &n, A, 10, B, 10 );
    exibir_vetor( "Uniao:", saida, n );

    return 0;
}

Exit:

Vetor A: 1 2 5 7 9 10 11 13 14 19
Vetor B: 1 3 5 7 8 10 11 12 14 16
Interseccao: 1 5 7 10 11 14
Uniao: 1 2 5 7 9 10 11 13 14 19 3 8 12 16

Browser other questions tagged

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