user3298889
user3298889

Reputation: 43

Random number generator without repeating numbers

I am trying to create a random number generator without repeating numbers {0 - 7}.

im getting a seg fault error here, and im pretty sure im allocating all the memory correctly there. One solution that i found that works occasionally is if i set shuffledbracket parameter size to 9. however since it has one extra memory it puts in an extra 0. any ideas on how i could get my array to only have a parameter size of 8 without a seg fault error?

Upvotes: 1

Views: 187

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158449

8 is not a valid index into shuffledbracket the indices of a C++ array are 0 to N-1, in this case 0 to 7, so you need to modify your loop:

for (int i = 7; i >= 0; i--)
           ^^^    ^^^

this introduces another problem since modulus by 0 is undefined behavior:

randnumero = rand()%i;
                   ^^

If you want to generate a random number from [M,N] you can use this formula from the C FAQ entry How can I get random integers in a certain range?:

M + rand() / (RAND_MAX / (N - M + 1) + 1)

or you could use the random header and uniform_int_distribution:

std::uniform_int_distribution<int> dist(0, i);

Upvotes: 2

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

Arrays in C++ start from 0. Therefore your for loop is invalid. Instead of:

for (int i = 8; i > 0; i--)

It should be

for (int i = 7; i >= 0; i--)

Besides that, there's obviously no hehe variable.

Upvotes: 3

Related Questions