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 ()

preguntado el 24 de agosto de 12 a las 01:08

Where is the array? -

It's very unclear what you really want to do. Do you want your 'tasks' to run once for each possible combination of elements, or do you won one task or the other to run run only if there is any matching elements or not across the entire arrays? In other words, if you had two arrays that look like {1, 2, 3} y {4, 5, 6}, would you like the 'no match' task to run once or 9 times? -

I would like 'no match' to run only once. Thanks -

1 Respuestas

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
    }
  }
}

Tenga en cuenta que el "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;
}

Entonces úsalo.

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
    }
}

Respondido 24 ago 12, 01:08

Thanks jonathon. Can you explain to me some more why its better to use char? I intend to use with an array with integer elements, plus i have to deal with many thousand elements. - fclopez

Then use int. It was just an example. - jonathan reinhart

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.