首页 > 解决方案 > 如何在数组中找到不同的值

问题描述

我想在数组中找到相似的值。所以如果值不相似,计数器将加一。代码:

struct station{
    int d; //destination, one-way journey, no return
    int counter;
    int depart[10];
};
int main()
{
    int n = 0; //number of stations
    int k = 0; //k is how many route one station can go

    scanf("%d%d",&n, &k);

    //declare array of stations based on input, n.
    struct station list[n];

    //Initialization
    for(int i=0; i < n; i++){
        list[i].d = 0;
        list[i].counter = 0;
    }

    for(int i=0; i < n; i++){
        int to;
        scanf("%d", &to);
        list[i].d = to-1;
    }

   //this is where the problem is
    int ds = 0; //depart station 
    for(int ds=0; ds < n; ds++){ // n is number of station

        list[ds].depart[list[ds].counter] = ds;
        list[ds].counter = list[ds].counter + 1;

        int next = list[ds].d;
        for( int j = 0; j < k; j ++){ //k is how many route one station can go**

            list[ next ].depart[ list[ next ].counter ] = ds;

            if(list[ next ].depart[ list[ next ].counter ] != list[ next ].depart[ list[ next ].counter -1 ] ){
                list[ next ].counter = list[next].counter + 1;
            }
            next = list[next].d;
        }
    }

    for(int i=0; i < n; i++){
        printf("station [%d]: counter = %d: ", i+1 , list[i].counter);
        for(int j=0; j < list[ i ].counter; j++){
                if (list[i].depart[j] != list[i].depart[j-1] ){
                    printf("%d,", list[i].depart[j] );
            }
            }
        printf("\n");
    }

    return 0;
}

输入:

5 3  
2  
3  
1  
4  
5  

输入以一种方式输入:(
站数)(一个站可以走多少条路线)
(站 1 去)
(站 2 去)
(站 3 去)
(站 4 去)
(站 5 去至)

这是我当前的输出:

station [1]: counter = 3: 1,2,3  
station [2]: counter = 2: 2,3  
station [3]: counter = 2: 2,3  
station [4]: counter = 2: 4,5  
station [5]: counter = 2: 4,5  

注意:站 2 和 3 应该在输出中显示 1,而不仅仅是 2 和 3。

我以前试过这个:

    int ds = 0; //depart station 
    for(int ds=0; ds < n; ds++){ // n is number of station

        list[ds].depart[list[ds].counter] = ds;
        list[ds].counter = list[ds].counter + 1;

        int next = list[ds].d;
        for( int j = 0; j < k; j ++){ 

            list[ next ].depart[ list[ next ].counter ] = ds;
            list[ next ].counter = list[next].counter + 1;

            next = list[next].d;
        }
    }

输出将如下所示:

station [1]: counter = 4: 1,1,2,3  
station [2]: counter = 4: 1,2,2,3  
station [3]: counter = 4: 1,2,3,3  
station [4]: counter = 4: 4,4,5,5
station [5]: counter = 4: 4,4,5,5  

标签: c

解决方案


推荐阅读