((C ++)使一组数字1-3成为随机序列

问题描述 投票:-5回答:3

我需要我的程序每次从1-3中随机生成一个序列,但是我不明白如何使用rand()使每个程序中数字1到3的排列顺序不同。它不能再是相同的数字,所以我不知道该怎么做。运行示例为

123第一,231第二,321等第四

您将使用什么来制作不重复数字的序列

c++ random sequence
3个回答
1
投票

生成序列的最简单方法是使用std::shuffle重新排序包含所需值的向量:

#include <vector>
#include <algorithm>
#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 g(rd());
    std::vector<int> elements = { 1, 2, 3 };
    std::shuffle(elements.begin(), elements.end(), g);
    for (int i : elements)
    {
        std::cout << i << "\n";
    }
}

如果您确实必须使用rand()(通常不是very good随机数生成器),您也可以将其压缩为shuffle

#include <vector>
#include <algorithm>
#include <ctime>
#include <iostream>

struct RandDevice
{
    using result_type = uint32_t;
    static result_type max() { return static_cast<result_type>(RAND_MAX); };
    static result_type min() { return 0; };

    result_type operator()() {
        return static_cast<result_type>(rand());
    }
};

int main()
{
    std::vector<int> elements = { 1, 2, 3 };
    srand(time(0));
    std::shuffle(elements.begin(), elements.end(), RandDevice());
    for (int i : elements)
    {
        std::cout << i << "\n";
    }
}

0
投票

您可以使用std :: next_permutation

示例:https://en.cppreference.com/w/cpp/algorithm/next_permutation


0
投票

这很容易..只需将您的数字与数组中每个占用的元素进行比较即可。如果它不在数组中,则添加到数组。否则,请重试。

我已经完成类似的代码检查了

    #include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void displayArray(int randNum[], int elements);
void randomNum(int randNums[], int elements);
int main ()
{
    //declare array
    int numbers[999] = {0};
    //random number generator
    srand(static_cast<int>(time(0)));

    randomNum(numbers, 999);
    displayArray(numbers, 999);

system("pause");
return 0;
}
void randomNum(int randNums[], int elements)
{
    for (int i = 0; i < elements; i++)
    {
        bool same;
        do
        {
            same = false;
            randNums[i] = rand() % 999 + 100;
            // Check if the newly generated number is a duplicate:
            for (int check = 0; check < i; check++)
            {
                if (randNums[i] == randNums[check])
                {
                    same = true;
                    break;
                }
            }
        } while (same);
    }
}
void displayArray(int randNum[], int elements)
{
    for (int sub = 0; sub < elements; sub ++)
    {
        cout << "Unique Numbers: " << randNum[sub] << endl;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.