如何合并两个没有重复的数组?

时间:2018-06-10 00:20:45

标签: c arrays merge flags sentinel

我是初学者。我认为我的主要问题是旗帜。 (我不能使用break命令来停止循环)。例如:

A={1,2,3,4,5} B={1,2,3,6} 

我必须使用之前的数组生成一个新数组,没有重复。所以:C = {1,2,3,4,5,6}。

#include <stdio.h>
#include <stdlib.h>

#define M 5
#define N 4
int main() {

int A[M]={1,2,3,4,5};
int B[N]={1,2,3,6};
int U[M+N]; //M+N is the maximum size. it'll decrease with a counter.

int i=0, j=0,count=0,flag=0;

while(i<M){           //Array A is copied into Array U.
U[count]=A[i];
count++;        //counter that will determine the size.
i++;
}

i=0,j=0;  

while(i<M){     
    j=0;
    flag=0;
while(flag==1 || j<N){         //check if the flag is on or if the array is ended.
    if(B[j]!=A[i]){               // check if the element of the b array is different from
                                            //the element of array A (cause i already copied the array A)
        count++;                                //i make some space for the element to be copied.
        U[count]=B[j];            
    }
    else flag=1;                            //if the flag is on it means the element was equal, so i just
    j++;                                        //go to the next one
}       
i++;
}

for(i=0;i<count;i++)
printf(" %d ", U[i]);       //here i print, it prints the first 5 values from Array a correctly, for the other ones is a mess.

return 0;
}

我的想法是将最长的数组(A)复制到新的数组(C),然后扫描第二个数组(B)并使用数组A的每个值检查每个值。如果值不同(全部A)中的值我将B值添加到C中,否则我开始用A中的所有值检查数组B的下一个值。

2 个答案:

答案 0 :(得分:0)

定义大小为M的数组A和大小为N的数组B. 在嵌套的while循环中,使用N检查i(与数组A一起使用的索引)。您只是混合了数组大小。

while(i<N){     
    j=0;
    flag=0;
    while(flag==1 || j<M){         
        if(B[j]!=A[i]){               
            count++;                               
            U[count]=B[j];            
        }
        else 
            flag=1;                            
        j++;                                        
    }   
i++;
}

答案 1 :(得分:0)

好吧,经过一番尝试,我想出了这个。

#include <stdio.h>
#include <stdlib.h>


#define F 5
#define S 4
#define L F+S

int main() {
    int A[F]={1,2,3,4,5};
    int B[S]={1,5,6,7};
    int U[L];

    int i=0,j=0,x=0, count=F, flag=1;

    printf("Primo vettore:\n");
    for(i=0;i<F;i++){     
        printf("%d ", A[i]);
    }

    printf("\n");

    printf("Secondo vettore:\n");
    for(i=0;i<S;i++){     
        printf("%d ", B[i]);
    }

    printf("\n");

    for(i=0;i<F;i++){     //i copy each element of array A to array B.
        U[i]=A[i];
    }

    for(i=0;i<S;i++){
        flag=1;
        x=0;
        for(j=0;flag==1 && j<F;j++){
            if(A[j]==B[i]){
            flag=0;
            }
        }
        if(flag==1){
            U[count]=B[i];
            count++;
        }
    }

    printf("Vettore generato:\n");
    for(i=0;i<count;i++)
    printf(" %d ", U[i]);


    return 0;
}

感谢大家的帮助!