+ 4

How to avoid repetition of random numbers in C++?

Example This code: srand(time(0)); for(int x=0;x<5;x++) { int r=rand()%5; cout<<r<<" "; } Output 0 3 2 3 1 But i want to avoid the repetition and i want the output to be : 4 2 3 1 0 Any idea ?

28th Nov 2019, 11:59 AM
$p@rK
$p@rK - avatar
6 odpowiedzi
+ 6
I think what you should be asking is, "How do I shuffle the list {0,1,2,3,4}". This is not so much about generating random numbers, you are actually trying to find a so-called "permutation of a list"! And, C++ can do it for you: #include <iostream> #include <algorithm> #include <iterator> int main () { using namespace std; int v[] = {0,1,2,3,4}; random_shuffle(begin(v), end(v)); for(int i : v) cout << i << endl; } If you want to "do it yourself", you can google the Fisher-Yates algorithm to shuffle a list. It's really simple actually! I see what you were going for in your code and it almost works. One problem is that your for loop probably needs to run a lot more often than 5 times though (it's random how often).
28th Nov 2019, 12:41 PM
Schindlabua
Schindlabua - avatar
+ 2
Keep track of already used numbers by using Array and check Everytime if new generated number is in array or not
28th Nov 2019, 12:08 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
I tied but doesn't work
28th Nov 2019, 12:09 PM
$p@rK
$p@rK - avatar
+ 2
Show me your try, then I can figure out what is problem 😉
28th Nov 2019, 12:10 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 1
int a[]={1,2,3,4,5}; srand(time(0)); for(int x=0;x<5;x++) { int c=rand()%5; int b=rand()%5; if(c==b) {} else{cout<<a[c];} }
28th Nov 2019, 12:13 PM
$p@rK
$p@rK - avatar
+ 1
Woah thank you so much man 👍👍👍👍👍👍
28th Nov 2019, 12:44 PM
$p@rK
$p@rK - avatar