gpt4 book ai didi

c - 如何输出随机生成的整数数组中第一个重复数字的索引 (C)

转载 作者:行者123 更新时间:2023-11-30 15:24:44 25 4
gpt4 key购买 nike

我正在尝试用 C 语言编写一个程序,它将生成 0-99 之间的 50 个随机整数,然后打印出来或抛出到第一个重复数字出现的索引处的变量。我认为使用数组是解决这个问题的最佳方法。我似乎成功地生成了一个随机(足够随机)整数数组并将它们放入一个数组中。

但是,在比较数组的每个元素时,我的 for 循环遇到了问题。看来我最终将索引 1 与索引 1 进行了比较并获得了匹配。
这是我当前的代码供引用。任何帮助/建议将不胜感激 - 我是编程新手:)

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

int main()
{
//define the test pool(N - people in the birthday problem)
//and possible unique attributes(M - birthdays in the birthday problem)
int N = 50;
int M = 100;
int i;
int x;
int y;
int arr[N];
int count = 1;

//use for loop to populate an array of length N with numbers ranging
//from 0 to 99
for(i = 0; i < N; i++)
{
arr[i] = rand() % (M-1);
printf("%d\n", arr[i]);
}

//just formatting the output a little
printf("\n\n\n");


//iterate through the array at each position, comparing it to all other
//positions in the array. if array[x] does not equal array[y] increment
//the counter. if it does match, print the counter to the screen.
for(x = 0; x < N; x++)
{
for(y = 0; y < N; y++)
{
if(arr[x] != arr[y])
{
count++;
}
else
{
printf("the first repeat is at: ");
printf("%d\n", count);
break;
}
break;
}
break;
}

return 0;

}

最佳答案

你必须改变

 for(y = 0; y < N; y++)

 for(y = x + 1; y < N; y++)

因为,当您选择一个元素x时,您必须在x的剩余数组前面中搜索其重复项,因此, y=x+1N。如果您再次开始从 y=0 开始搜索重复项,您最终会在 x 或之前找到 x 的重复项。

更好的方法:

在您的实现中,您必须运行两个循环来检查重复项。更快的方法是记录 counter 数组中出现的每个数字的计数,并仅运行一个循环,检查 counter[ arr[i] ] > 1 ,这意味着元素 arr[i] 已至少重复一次。

代码:

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

int main()
{
//define the test pool(N - people in the birthday problem)
//and possible unique attributes(M - birthdays in the birthday problem)
int N = 50;
int M = 100;
int i;
int x;
int y;
int arr[N];
//Counter[M] will store the number of occurences
//of M in the program;
int counter[M];
int count = 1;

for(int i = 0;i < 100; ++i)
{
counter[i] = 0;
}
//use for loop to populate an array of length N with numbers ranging
//from 0 to 99
for(i = 0; i < N; i++)
{
arr[i] = rand() % (M-1);
printf("%d\n", arr[i]);
counter[arr[i]]++;
//^^^^^^^^^^^^^^^ Incrementing the count array
//of the particular element arr[i].
}

//just formatting the output a little
printf("\n\n\n");


//iterate through the array at each position, comparing it to all other
//positions in the array. if array[x] does not equal array[y] increment
//the counter. if it does match, print the counter to the screen.
for(x = 0; x < N; x++)
{
if (counter[arr[x]] > 1)
{
printf("the first repeat is at: ");
if (youWantTheIndex)
{
printf("%d\n", x); //This prints the index
}
else if (youWantTheElement)
{
printf("%d\n", arr[x]); //This prints the element.
}
break;
}
}
return 0;

}

关于c - 如何输出随机生成的整数数组中第一个重复数字的索引 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28271922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com