简体   繁体   中英

Comparing values in two different arrays for equality

I'm trying to compare two different arrays for equality between all values, except the one in the same position in the other array: for example array1[0]==array2[1] but not array1[0]==array2[0] I'm having a little bit of trouble and know there must be an easier way than what I'm doing which is this: This is in c by the way

for(int r=1; r<4;4++){
    if(choicearray[r]==comparray[r+1]||choicearray[r]==comparray[r-1] || choicearray[r]==comparray[r+2]|| choicearray[r]==comparray[r-2] || choicearray[r]==comparray[r-3] || choicearray[r]==comparray[r+3]){
    printf("w "); 
         e++;
   }
  } 

Both arrays contain 4 characters

First of all remember that array are indexed starting from 0 (in your case 0 to 3).

You have to loop throught the first array then loop through the second array.

int n=4;
for(int r=0; r<n; r++){
    for(int q=0; q<n; q++){
        if(arrayA[r]==arrayB[q] && q!=r)
             printf("w ");
    }
}

The condition q!=r check that only different indexes are compared.

For starters, you can try to use two loops, each to control iteration of one array like so:

for (int r=0; r<4;r++){
    for (int s=0; s<4;s++){
        if (s!=r){
            //do your comparing
        }
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM