生成0到7之间的8个唯一随机数 [英] Generate 8 unique random numbers from 0 to 7

查看:834
本文介绍了生成0到7之间的8个唯一随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的脚本,该脚本会生成从0到7的8个随机值,并将它们存储到名为random_numbers的数组中.

I'm making a simple script that generates 8 random values from 0 to 7 and stores them into an array named random_numbers.

这是我的尝试:

int main(int argc, char** argv) {

    int random_numbers[8];
    srand((unsigned)time(NULL));
    for (int i = 0; i < 8; i++) {
        random_numbers[i] = 1+ rand() % 8;
        cout << random_numbers[i] << endl;
    }
    return 0;
}

这给了我重复的价值观.我希望random_numbers填充从0到7的随机值,但没有任何重复的数字.

This gives me repeated values. I would like to have random_numbers filled of random values from 0 to 7, but without any repeated numbers.

我该怎么做?

推荐答案

生成数字0到7,然后对其进行随机排序.假设这实际上是C ++,而不是C(由于cout),请使用std::random_shuffle:

Generate the numbers 0 through 7, then shuffle them. Assuming this is actually C++, not C (because of the cout), use std::random_shuffle:

#include <algorithm>
#include <cstdlib>
#include <iostream>

int main()
{
    int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
    std::srand(unsigned(std::time(0)));

    std::random_shuffle(a, a + 8);

    for (int i=0; i<8; i++)
        std::cout << a[i] << " ";
    std::cout << std::endl;
}

请注意: cppreference.com声明随机数生成器是实现定义的,但通常使用功能std::rand."我已经用std::srand植入了该种子,但是显然这并不是完全可移植的.

Be warned: cppreference.com states that "The random number generator is implementation-defined, but the function std::rand is often used." I've seeded that with std::srand, but apparently that's not completely portable.

这篇关于生成0到7之间的8个唯一随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆