如何匹配数组中的多个值?

时间:2014-03-14 20:42:15

标签: c arrays match

我想知道如何匹配数组中的多个值。

例如:

int set[7] = {1,3,5,7,9,11,42};

int new_array[7];

for(int i =0;i<7;i++)
   scanf("%d",&*(new_array + i));

for(int i=0;i<7;i++)


if(new_array[i] matches 5 numbers in set[i])// let's say numbers entered match 5 numbers in the set array

   do something;

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>

int find(int n , int array[n], int value){
    //array is sorted in ascending order
    int low = 0, high = n - 1;
    while(low <= high){
        int mid = (low + high)/2;
        if(array[mid] == value)
            return mid;
        if(array[mid] < value)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;//not found
}

int main(){
    int set[7] = {1,3,5,7,9,11,42};
    int new_array[7];
    int match[7], mcount=0;

    for(int i =0;i<7;i++){
        scanf("%d", &new_array[i]);
        if(find(7, set, new_array[i]) != -1){
            match[mcount++] = new_array[i];
        }
    }
    if(mcount >=5)
        //do something;
        for(int i=0;i<mcount;++i)
            printf("%d ", match[i]);
    return 0;
}