Since you already know the range of the sequence, and it's small, and you want non-repeating values, a random shuffle would be a better option than trying to check whether each new number was already generated or not:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 157
int main ( void )
{
int seq[N];
int i;
srand ( (unsigned)time ( NULL ) );
/* Initialize seq to an ordered range */
for ( i = 0; i < N; i++ )
seq[i] = i;
/* Random shuffle */
for ( i = 0; i < N - 1; i++ ) {
int r = ( rand() % ( N - i ) + 1 );
int save = seq[i];
seq[i] = seq[i + r];
seq[i + r] = save;
}
/* Test the sequence */
for ( i = 0; i < N; i++ )
printf ( "%d ", seq[i] );
return 0;
}
Not only is it easier to verify, it's also considerably faster.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Sometimes the standard library makes life easier:
#include <algorithm>
/* Random shuffle */
std::random_shuffle(seq, seq + N);
Obviously not useful since we already have an implementation, but useful if you'll need it elsewhere.
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
>Sometimes the standard library makes life easier
Indeed. But since the original problem was clearly written in C, the C++ standard library is hardly useful. You might argue that C compiles as C++, so it's not a problem, but since you would be wrong, I recommend that you don't bother, and save yourself the intellectual manbeating I'll give you if you try. :D
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Oh man, what was I thinking?
Never mind then. :o
(It's not a question of whether C can compile to C++; C++ simply can't be compiled as C! ;-) )
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177