Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

visual c++ - C++ random number generator without repeating numbers

I have searched high and low for a type of function that turns this code

#include <iostream>
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

using namespace std;

void ran(int array[], int max);
int main() {
 printf("Today's lottery numbers are:
");    
 for (int i = 0; i < 6; i++)
  srand((unsigned)(NULL));
}

into a random number generator that ensures no repeating numbers can someone help me with it? after the check I plan to print it with printf("%d ", rand()%50);

I just need a routine that makes sure its non repeating. Please If you can give me a routine I would be greatly relieved and will be sure to pay it forward.

Thanks. The libraries don't seem to be reading right on this scren but they are stdio, stdlib and time and im using namespace.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not just use what's already in the STL? Looking at your example code, and assuming it's somewhat representative of what you want to do, everything should be in there. (I assume you need a relatively small range of numbers, so memory wouldn't be a constraint)

Using std::random_shuffle, and an std::vector containing the integers in the range you wish your numbers to be in, should give you a sequence of unique random numbers that you need in your example code.

You will still have to call srand once, and once only, before using std::random_shuffle. Not multiple times like you're doing in your current code example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...