我用 srand 在 C++ 中构建非重复随机数组做错了什么?
我正在尝试构建一个长度为(size1)的随机数组。我研究的方法是拥有两个单独的数组,一个用于我的随机数,另一个用于“检查”数组以确保数字不会重复。这些在我的代码中分别标记为(随机播放)和(访问)。 count1 是一个整数,用于通过我的 for 循环进行计数。
我已将以下内容包含在不同的组合中,但它没有起作用。
#include <ctime>
#include <time.h>
#include <cstdlib>
我似乎正在努力解决的代码是这样的:
srand((unsigned)time(0));
for (count1 = 0; count1 < size1; count1++)
{
num = (rand()%size1);
if (visit[num] == 0)
{
visit[num] = 1;
shuffle[count1] = num;
}
}
I am trying to build a random array of length (size1). The way that I've researched doing this is to have two separate arrays, one for my random numbers and a secondary "checking" array to make sure the numbers don't repeat. These are labeled (shuffle) and (visit) in my code respectively. count1 is an integer for counting through my for loop.
I have included the following in different combinations and it hasn't worked.
#include <ctime>
#include <time.h>
#include <cstdlib>
The code I seem to be struggling with is this:
srand((unsigned)time(0));
for (count1 = 0; count1 < size1; count1++)
{
num = (rand()%size1);
if (visit[num] == 0)
{
visit[num] = 1;
shuffle[count1] = num;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用 srand 没有任何问题。但是,您描述的任务非常简单,并且不涉及
rand
函数的使用。如果您没有 iota 函数,它只会生成一个递增的整数序列。
There's nothing wrong with your usage of srand. But, the task you describe is very simple, and doesn't involve the use of the
rand
function.If you don't have the
iota
function, it just generates an incrementing sequence of integers.用数字 0 到 size1-1 填充数组,然后打乱这些数字会更容易。
所以在类似c的代码中(很长一段时间没有使用c):
然后对其进行洗牌
基本上,对于数组中的第一个元素,选择任何索引并切换值。现在第一个索引是随机选择的。对于第二个元素,选择一个随机索引(不包括第一个,因为它已经被随机选择)并执行相同的操作。重复直到到达最后一个元素。
It is easier to fill your array with the numbers 0 to size1-1 and then shuffle those numbers.
So in c like code (haven't used c in a long time):
and then shuffle it
Basically, for the first element in the array, select any index and switch the values. Now the first index is randomly selected. For the second element, select a random index (excluding the first as that has already been randomly selected) and do the same. Repeat until you get to the last element.
您的#include 不是问题。问题是:当您生成的第一个数字已被使用时,您不会尝试生成备用数字。
您应该在 for 循环内包含一个
while
循环,该循环会不断生成新数字,直到找到一个有效的数字。现在的写法是,如果您为
size1
= 5 生成序列4,1,4,2,4
,您的数组最终将如下所示:假设每个条目最初设置为
0
。这是因为您将跳过为其生成两个额外4
的索引。Your
#include
s are not the problem. The problem is: you are not trying to generate alternate numbers when the first one you generate has already been used.You should include a
while
loop, inside the for loop, which keeps generating new numbers until you find one that works.They way it's written now, if you generate the sequence
4,1,4,2,4
forsize1
= 5, your array will end up looking like this:Assuming each entry was set to
0
initially. This is because you will just skip over the indices for which the two extra4
s were generated.