我需要在二维数组中找到重复的元素。
route_ptr->route[0][1] = 24;
route_ptr->route[0][2] = 18;
route_ptr->route[1][1] = 25;
route_ptr->route[2][1] = 18;
route_ptr->route[3][1] = 26;
route_ptr->route[3][2] = 19;
route_ptr->route[4][1] = 25;
route_ptr->route[4][2] = 84;
这些是我的数据;必须找到 route[2][1](route[0][2] 的副本)和 route[4][1](route[1][1] 的副本)的重复条目。
解决方案是 route[i][j] 的重复 'i' 值,即本例中的 2 和 4。
请指导我。
#include <stdio.h>
struct route{
int route[6][6];
int no_routes_found;
int count_each_route[6];
};
int main() {
struct route *route_ptr, route_store;
route_ptr=&route_store;
int i,j,k;
// the data
route_ptr->route[0][1] = 24;
route_ptr->route[0][2] = 18;
route_ptr->route[1][1] = 25;
route_ptr->route[2][1] = 18;
route_ptr->route[3][1] = 26;
route_ptr->route[3][2] = 19;
route_ptr->route[4][1] = 25;
route_ptr->route[4][2] = 84;
route_ptr->count_each_route[0]=3;
route_ptr->count_each_route[1]=2;
route_ptr->count_each_route[2]=2;
route_ptr->count_each_route[3]=3;
route_ptr->count_each_route[4]=3;
route_ptr->no_routes_found=5;
//// process
for (i = 0; i <(route_ptr->no_routes_found) ; i++)
{
for (j = 1; j < route_ptr->count_each_route[i]; j++)
{
printf("\nroute[%d][%d] = ", i, j);
printf("%d",route_ptr->route[i][j]);
}
}
}
预期的解决方案是:
route[0][1] is compared by route [0][2] i.e [24 !=18]
route[0][1] and route [0][2] is compared by route[1][1] i.e [24 && 18 !=25]
route[0][1] and route[0][2] and route[1][1] is compared by route[2][1] i.e [ 24&&18&&25 is compared by 18, there is a matching element,
save the newcomer 'i' value which matches to the existence and drop it for next checking]
break the 'i' loop
route[0][1], route[0][2], route[1][1] is now compared route[3][1]
route[0][1], route[0][2], route[1][1] ,[3][1] is now compared route[3][2]
route[0][1], route[0][2], route[1][1] ,[3][1] ,[3][2] is now compared to route [4][1] i.e [ now there is a match to route[1][1], so save the newcomer 'i' value and break the 'i' loop
所以 i 值 [2 和 4] 是重复的,这是我的代码的预期结果。