+ 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 ?
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).
+ 2
Keep track of already used numbers by using Array and check Everytime if new generated number is in array or not
+ 2
I tied but doesn't work
+ 2
Show me your try, then I can figure out what is problem 😉
+ 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];}
}
+ 1
Woah thank you so much man 👍👍👍👍👍👍