我正在尝试使用数组来修正一个程序,它在0到24之间得到随机数,但它们只能出现一次。 我知道如何生成随机数,我只是坚持如何检查数字中是否已存在数字。我尝试生成一个新的rand()%25并将其与数组中的占位符进行比较,如果它不存在则将新的随机数放在那里,但它不起作用。
void MultiU (){
int size = 5;
int array[5];
srand(time(0));
for (int index = 0; index < size; index++){
exists[index] = rand() %25;
}
}
我是使用数组和rand()进行编程的新手。我希望有人可以指导我朝着正确的方向前进。
答案 0 :(得分:9)
std::unordered_set
是你的朋友。它不允许/插入重复项,您可以利用这一事实获得5个不同的数字。当集合大小为5时,保证包含5个不同的元素。
std::unordered_set<int> s;
while (s.size() < 5) {
s.insert(rand() % 25);
}
答案 1 :(得分:5)
这是获取没有重复的随机数列表的一般方法:
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
int main() {
std::vector<int> vals;
for (size_t i = 0; i < 25; ++i) {
vals.push_back(i);
}
std::shuffle(vals.begin(), vals.end(), std::mt19937());
for (auto v : vals) {
std::cout << v << std::endl;
}
}
在这种情况下,这样做效率低,然后只提取前五个数字。然而,随着可能的随机数列表变得越来越大(并且你想要选择更多的随机数),这种方法将比The Paramagnetic Croissant的方法更有效。
我还应该补充一点,你不应该使用rand()
。或者尝试使用带有模数的rand()
来获得固定范围的随机数。它们将无法正确分发!
答案 2 :(得分:2)
以下是您要执行的操作的伪代码: - 1)首先生成一个随机数
int number = rand() %25;
2)检查数组中是否存在“数字”。
3)如果没有,则插入else转到步骤1;
除此之外,还有比利用普通阵列更有利可图的选择(容器)。
编辑回应评论#
您可以为此定义一个函数,并在上面提到的步骤2中调用它: -
bool search ( int *p, int size, int element )
{
for( int i = 0; i < size; i++ )
{
if ( *(p+i) == element )
return false;
}
return true;
}
在这种情况下,哈希表非常有效,如果它包含在你的类中。
答案 3 :(得分:0)
您可以使用Fisher–Yates_shuffle:
// Fisher–Yates_shuffle
std::vector<int> FisherYatesShuffle(std::size_t size, std::size_t max_size, std::mt19937& gen)
{
assert(size < max_size);
std::vector<int> res(size);
for(std::size_t i = 0; i != max_size; ++i) {
std::uniform_int_distribution<> dis(0, i);
std::size_t j = dis(gen);
if (j < res.size()) {
if (i < res.size()) {
res[i] = res[j];
}
res[j] = i;
}
}
return res;
}
答案 4 :(得分:0)
检查此代码:
int numbers[26], tempNum; //Array required to store the used values and tempNum for the random number you want to generate
bool x; //This will be required later (true or false)
srand(time(0));//I think you have this clear
for(int i = 0; i <= 24; i++){//Required in order to generate 24 random numbers
do{
tempNum = (rand()%25);//Generates the random number
x = false;//This sets the value as not used before
for(int j =0; j <= 24; j++){//Scans the array to find out whether the value is used before
if(tempNum == numbers[j]){//Tests if the value is used before
x = true;// If so marks it as used
}
}
}while(x == true);//This makes it go back to generating a new number part
numbers[i] = tempNum;//This stores the number in the array
cout << tempNum << endl;//Prints the number on the screen
}
答案 5 :(得分:0)
显而易见的解决方案是创建一个可接受的向量
值,随机随机播放,并取第一个n
:
std::vector<int> values( 25 );
for ( int i = 0; i != 25; ++ i ) {
values[i] = i;
}
std::random_shuffle( values.begin(), values.end() );
values.resize( size );
应该这样做。