c - 如何在数组中找到不同的值
问题描述
我想在数组中找到相似的值。所以如果值不相似,计数器将加一。代码:
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
解决方案
推荐阅读
- blazor - Blazor - 是否使用@
- c++ - 如何重新打印 C++ 打印请求文件
- javascript - 粘贴纯文本时如何更改tiptap 的行为?
- c# - 如何每 5 秒运行一次任务以对 IP 地址运行 ping
- javascript - 使用打字稿在浏览器中运行 mocha
- laravel-5 - 在没有主键但在多个重叠字段上加载模型一对多关系的雄辩方式
- nginx - Rasa X Helm Chart 安装的 HTTPS 不起作用
- html - 如何创建动态拖放占位符(HTML 或角度 CDK)
- javascript - 如何指定命令的选项?
- c++ - 传递可变数量的不同参数并在 C++ 中调用函数