I have this:
#include <iostream>
using namespace std;
int main()
{
int a[256];
int b;
int k;
for (int i = 0; i < 256; i ++){
b = rand()%256;
k = 0;
for (int j = 0; j< i; j ++)
{
if (a[j] == b){k = 1;}
}
if (k == 0){a[i] = b;}
if (k==1){i--;}
}
return 0;
}
This generates an array of integers from 0 to 255. Each integer only occur once in the array. My problem is that this code takes quite a while to execute because for each new random integer I check whether or not the integer is already in the array. So I have to wait until all the integers from 0 to 255 have showed up as a random number. My question is:
Is there is a better way to do this?
As others mentioned, use std::random_shuffle:
You could try something like this:
std::random_shuffle
is the way to go, as previously mentioned, but just in case you don't want to use it (maybe using ANSI C instead of C++), here's a quick-and-dirty implementation: