fclopez
fclopez

Reputation: 55

Compare elements of an array to all elements of another array

I would like to compare each element of one array to all elements of another array. What I want to achieve is if an element exists in another array, result =0, otherwise result =1

int m,n;

for(int i=0; i<m; i++) {
  for(int j=0; j<n; j++) {
    if(i==j) {
      result =0;
      //perform a task
       break;
    } 

     if(i!=j) {
       result = 1;
      //perform another task
      break
     }

  }
}

however, i fail to achieve what i want in the second if ()

Upvotes: 1

Views: 22078

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Tweaking your code somewhat (replace char with whatever datatype you're actually using):

char A[50];
char B[50];

for(int i=0; i<50; i++) {     // Iterate through A from 0 to 50
  for(int j=0; j<50; j++) {   // Iterate through B from 0 to 50
    if(A[i] == B[j]) {
       // Item from A exists in B
    }
    else {
       // Item from A does not exist in B
    }
  }
}

Note that the "else" code will run once for every element.

We can do better. First make a utility function that searches an array:

bool item_exists(char item, char[] array, int array_len) {
    for (int i=0; i<array_len; i++) {
       if (array[i] == item)
          return true;
    }
    return false;
}

Then use it.

char A[50];
char B[50];

for(int i=0; i<50; i++) {
    if (item_exists(A[i], B, 50)) {
       // Item from A exists in B
    }
    else {
       // Item from A does not exist in B
    }
}

Upvotes: 3

Related Questions