Hey all.
I know the actual topic of duplication (especially the removal of duplicates in arrays), is a common thread on this board. However, my question is more to do with efficiency than a piece of code that works.
Here's what I'd like to do at the moment, but I'm asking for future reference more than anything, as the efficiency isn't really a problem pertaining to this example.
I need to initialise an array with the values 0 - 9 in a random order, without any duplicates. Obviously, placing a seed, and then using rand() % 10 will start things off. Thing is, when it comes to preventing the duplication, the only way I can think of doing it, is with nested loops. Something like (untested):
(Code now without smilies in it lol)
The approach seems fine for something on such a small scale, but is there a more efficient way to tackle this for a program on a much larger scale?Code:#include <iostream.h> #include <stdlib.h> #include <time.h> const int ARR_SIZE = 10; int *init_arr(void); int main(void) { int *aptr; aptr = init_arr(); /* Cool program type stuff goes here. */ return 0; } int *init_arr(void) { int i, j; static int rvals[ARR_SIZE]; srand(time(NULL)); for (i = 0; i < ARR_SIZE; ) { rvals[i] = (rand() % 10); for (j = 0; j < i; ) { if (rvals[i] == rvals[j]) break; else j++; } if (j == i) i++; } return rvals; }
Thanks in advance.
John.