-3

Context : I'm searching for all the words contained in a 2d array (horizontally,vertically and diagonaly).

So what I do is I get all the possible words, check if they're in the given dictionary and if they are store them in an array. The thing is, I don't want it to have duplicates.

Here's a snippet of the code:

        for (i=l-1;i>=0;i--){
            palavra[aux]=mat[i][caux];
            for (j=i;j>=0;j--){
                palavra[aux]=mat[j][caux];
                palavra[aux+1]='\0';
                for (it=0;encontradas[it]!=NULL;it++){
                    if (strcmp(palavra,encontradas[it])==0)flag=1;
                    else flag=0;
                }
                if (flag==0) {
                    r = palavra_existe(dic,palavra);
                    if (r!=0) {
                        found[auxenc]=mystrdup(palavra);
                        auxenc++;
                    }
                }
                flag=0;                 
                aux++;
            }
            aux=0;
        }       

The

    if (strcmp(palavra, found[it])==0)flag=1

line is there to check if the formed worded has been found already, to avoid creating a duplicate. The problem is it doesn't work, duplicates appear anyway (as the flag variable never takes the value 1).

What could I be missing here?

user3690823
  • 35
  • 1
  • 2
  • 5
  • How does `encontradas` get populated? – kfsone May 30 '14 at 23:24
  • Is it never set to 1, or does it get reset to 0? Without studying the surrounding logic, you do not only set `flag` to 1 when `strcmp()` signals that the values are equal, you also set it back to 0 every time you find a value that is **not** equal. – Reto Koradi May 30 '14 at 23:26

1 Answers1

1

The flag variable does get the value 1, but then it turns back to 0 again in the next iteration.

Set flag to zero before the loop, and when you find a match you set it to 1 and exit the loop:

flag = 0;
for (it = 0; encontradas[it] != NULL; it++) {
  if (strcmp(palavra,encontradas[it]) == 0) {
    flag=1;
    break;
  }
}

(Exiting the loop isn't needed for the logic to work, but there is no point in looping through the rest of the items once you have found a match.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005