gpt4 book ai didi

c++ - 如何为同一个变量生成不同的随机数

转载 作者:行者123 更新时间:2023-11-30 03:18:38 24 4
gpt4 key购买 nike

我想用一个while循环为一个变量生成一个随机数来拼出一个乱码。我的问题是我的代码生成了一个随机数字,但重复该数字而不是使用新数字。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
string wordList[5] = {"cool", "friend", "helpful", "amazing",
"person"};
srand(time(0));
int rWord = rand() % 5 + 1;
string randWord = wordList[rWord];
int runs = 0;
int wordLen = randWord.length();
while(runs != wordLen){
int ranLN = rand() % wordLen;
char randLetter = randWord[ranLN];
cout << randLetter;
runs++;
}

return 0;
}

我原以为我的结果是一个完全乱序的单词,但我得到的却是重复的字母。例如,我把“friend”这个词拼成了“eennn”。

最佳答案

如评论中所建议,当前范围为 rWord1,2,3,4,5必须固定为 0,1,2,3,4 .因此我删除了 +1来自以下答案中的初始化方程。此外,ranLN可以重复,因此您得到了重复的字母。

然后,一种可能的方法是递归地洗牌 randWord 的所有字符并在 while 循环完成后输出它们,如下所示。显示了相同的算法 here举个例子:

DEMO

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <utility>

int main()
{
std::string wordList[5] = {"cool", "friend", "helpful", "amazing", "person"};

srand(time(0));

std::size_t rWord = rand() % 5;
std::string randWord = wordList[rWord];

std::size_t runs = 0;
std::size_t wordLen = randWord.length();

while(runs != wordLen)
{
std::swap(randWord[runs], randWord[rand() % wordLen]);
++runs;
}

std::cout << randWord << std::endl;

return 0;
}

顺便说一句,尽管rand()通常应该由更好的 LCG 来实现,但是,例如(我的本地)C++ 标准草案 n4687 中所述,rand() 中使用的算法是完全定义的编译器实现:

29.6.9 Low-quality random number generation [c.math.rand]

int rand();
void srand(unsigned int seed);

... rand’s underlying algorithm is unspecified. Use of rand therefore continues to be non-portable, with unpredictable and oft-questionable quality and performance.

幸运的是,在 C++11 及更高版本中,我们可以使用 <random>生成有保证的质量随机性。因此,我建议您将它们与 std::shuffle 一起使用如下。如果需要更高质量的随机性,可以使用std::mt19937而不是 std::minstd_rand :

DEMO

#include <iostream>
#include <string>
#include <random>
#include <algorithm>

int main()
{
std::string wordList[5] = {"cool", "friend", "helpful", "amazing", "person"};

std::minstd_rand gen(std::random_device{}());

std::uniform_int_distribution<std::size_t> dis(0, 4);
std::size_t rWord = dis(gen);
std::string randWord = wordList[rWord];

std::shuffle(randWord.begin(), randWord.end(), gen);
std::cout << randWord << std::endl;

return 0;
}

关于c++ - 如何为同一个变量生成不同的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535401/

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