Generating a sequence of numbers - C++

# Thread: Generating a sequence of numbers - C++

1. ## Generating a sequence of numbers - C++

I'm trying to generate a sequence of random numbers where each number in the sequence is random. The language of choice is C++.

Example:
Generate 100 different numbers between 1-100.

I plan to store them in a respectively-size array. I know I could generate a number and check the whole array for it, if so...then eliminate it...but I'm not sure if that's the best/easiest way to go about it.

A_T

2. my best idea so far is to put 1-100 in that array, and use rand () and swap() to just move the numbers around

A_T

3. Hi

Well what you can do is that generate a random number from the function rand().
Now you have a number that you want to limit between 100 then take the remainder of the number after dividing by 100. This way the numbers will always be between under 100.

Alternatively there may be a situation that the remainder of two numbers generated by rand() is same so if you want totally distinct numbers then you can compare them from previously generated numbers.

This way you dont have to store the numbers in array.

Code for generating 10 random numbers is
for(i=0;i&lt;10;i++)
{ printf("%d\n",rand()%100);
}

Hope it helps.

4. Code:
```#include &lt;cstdlib&gt;
...
int limiter = 100;
int limited;
srand(time(NULL));
limited = (int) (limiter * rand() / (RAND_MAX + 1.0)); // RAND_MAX = the max value that rand() can return, (int) casts it to an int, thus dropping whatever decimal there is
std::cout << limited << endl;
...```
srand(time(NULL)); sets the initial seed of rand() to the current time via the time(NULL) function (passing in a null pointer). you should generate non-repeating "random" numbers if there was an unlimited range. but you want 1-100, thus you will get some repeats using this method. thus i would initialize a system of checks. store the numbers in an array, vector, etc. and then compare incoming "random" numbers to those stored in the data structure.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•