2014-02-26 81 views
1

如何生成一个包含一组连续数字但具有随机顺序的数组?例如,连续的数字是从8到100(不重复),我想要的是一个包含所有这些数字的数组,但序列是随机的。以随机顺序连续编号

+0

听起来就像洗牌一样。 – jrok

+0

使用'std :: random_shuffle',看看这篇文章: http://stackoverflow.com/questions/21948091/how-to-generate-an-array-of-256-distinct-numbers/21948500# 21948500 – asamarin

+2

为什么你们不把你的评论发布为答案,而不是评论? – m01

回答

4

我想8和100都包含在范围内。

#include <algorithm> 
#include <numeric> 
#include <iterator> 

int main() 
{ 
    const size_t N = 93; 
    int a[N]; 

    std::iota(std::begin(a), std::end(a), 8); 
    std::random_shuffle(std::begin(a), std::end(a)); 
} 

如果8是在您的文章错字和你的意思是0,则该代码将如下

const size_t N = 101; 
    int a[N]; 

    std::iota(std::begin(a), std::end(a), 0); 
+0

thx! 8不是拼写错误〜 –

+0

什么是'std :: itoa'?我无法在我的标准副本中找到它(并且通过它的参数看起来不像旧版Unices中这个名称的功能)。 –

+0

@JamesKanze:http://www.cplusplus.com/reference/numeric/iota/ – lisyarus

0

我假设你是学生,新的节目,因此一些基本知识应该被告知。

rand()生成随机数。

如果你想让号码在一个特定的范围内,然后把它的mod例如

rand()%93; // generate random numbers from 0-92 

同样, (RAND()%93)8 //将生成8-100

之间数此外,用于检查重复您可以与那些已存储在数组中比较数。

+0

与已经生成的数字相比可能非常慢,而且时间成本高度依赖于使用的伪随机数生成算法。生成一个序列,然后洗牌是一个更好的主意,因为它的时间成本是线性的。 – lisyarus

+0

如果一个数字(比如说0)在无限的时间之后产生了什么? –