javierdemartin
javierdemartin

Reputation: 645

How to insert distinct elements into an array?

I am trying to insert distinct elements into a matrix. To do so I create an array of [rows x columns] dimension and place there each element I insert into the matrix and right after that read the array and if an element of the matrix is the same as one in the array make the user reintroduce the [m][n] element into the array. But doing so this doesn't work the way I expected and also looks a bit messy; how can it be more "simple"?

void rellenarMatriz(int **a, int f, int c) {

    int i, j, aux, k, l;

    for(i = 0; i < f; i++) {

        for(j = 0; j < c; j++) {

            //Introducir numero
            printf("    [%d][%d]> ", i+1, j+1);
            scanf("%d", &a[i][j]);

            //Comprobar que ese elemento no está en la matriz  
            contieneElemento(a, i, j);   
        }

        printf("\n");
    }    
}

NOTE: This is not homework, I am trying to learn on my own.

Solution?

void contieneElemento(int ** a, int ff, int cf) {

    int i, j;

    for(i = 0; i <= ff; i++) {

        for(j = 0; j <= cf; j++) {

            printf("[%d][%d]>\n", i + 1, j + 1);

            do {

                printf("> Elemento repetido.\n");
                printf("   *[%d][%d]> ", ff + 1, cf + 1);
                scanf("%d", &a[ff][cf]);
            } while(a[i][j] == a[ff][cf]);
        }
    }  
}

Upvotes: 0

Views: 1170

Answers (1)

D&#250;thomhas
D&#250;thomhas

Reputation: 10083

The simplest way is simply to look through your matrix/array to see whether or not the element you wish to insert is already there. I recommend you have a separate function that tells you.

bool ya_tiene_elemento( int **a, int f, int c, int hasta_f, int hasta_c, int elt )
{
  if (hasta_f > 0)
    for (int i = 0; i < hasta_f-1; i++)
      for (int j = 0; j < c; j++)
        if (a[i][j] == elt) return true;
  for (int j = 0; j <= hasta_c; j++)
    if (a[hasta_f][j] == elt) return true;
  return false;
}

That will suffice for a toy.

If you wish to be significantly more efficient, consider using a Bloom Filter to decide whether or not you wish to actually scan the matrix/array for a match.

Hope this helps.

Upvotes: 2

Related Questions