如何生成同一个变量不同的随机数

问题描述 投票:1回答:2

我想用一个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;
}

我希望我的结果是完全乱序的词,但我反而有重复的字母。例如,我炒为“eennn”的“朋友”一词。

c++
2个回答
2
投票

如在意见提出,rWord的电流范围是1,2,3,4,5必须被固定到0,1,2,3,4。因此,我删除+1从它下面的答案初始化式。此外,ranLN可以复制这样你有重复的字母。

然后,一个可行的办法是递归完成如下while循环之后洗牌randWord并输出的所有字符。同样的算法被示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低质量的随机数生成[c.math.rand]

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

...兰特的底层算法是不确定的。因此兰特的使用仍然是不可移植的,不可预知的和经常可疑的质量和性能。

幸运的是,在C ++ 11遍,我们可以使用<random>生成一个质量保证随机性。因此,我建议你如下与std::shuffle使用它们。如果您需要更多高质量的随机性,你可以改用std::mt19937std::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;
}

0
投票

在我所有的生成随机单词,然后用一组数据结构会使得随机字后独特拙见。

© www.soinside.com 2019 - 2024. All rights reserved.