[2 days left] Whatâ€™s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
Solved

# Random numbers from a specific range in C++

Posted on 2008-06-22
Medium Priority
3,206 Views
I want a function which will take random numbers from a range like this: from 2 to 120, excluding integers x and y and so on..

Thanks a lot..
0
Question by:Chrysaor
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 5
• 2
• 2
• +1

LVL 3

Assisted Solution

sistemu earned 400 total points
ID: 21840279

``````int rand(int maxVal)
{
int x = random(maxVal);
if((x>=2)&&(x<=maxVal))
return x;
else rand(maxVal);
}

int exclude(int x,y)
{
int value = rand(120);
if((value == x)||(value == y))
value = exclude(x,y);
return value;
}
``````
0

LVL 53

Expert Comment

ID: 21840321

``````#include <cstdlib>
#include <ctime>

// calculate a random value between min and max (inclusive)
int getRand(int min, int max) {
return min + (rand() % (max - min + 1));
}

int main(void) {
srand(time(0));               // <--- call this once at the start of the application

int value = getRand(2, 120);  // <--- the random value between 2 and 120 (inclusive)

return 0;
}
``````
0

Author Comment

ID: 21840576
To Infinity08: What happens for the numbers I want to exclude?

To sistemu: From what I understand, in both functions rand and exclude, if the numbers we don't want are assigned to our integers, it goes from the start and assign a new random number to our integer, and it is bit time consuming. Because what I'm trying to do has time limit, and I am going to perform these random calculations million times, and the application does get a little slow, is there any other way, faster?

Thanks a lot guys..
0

LVL 53

Expert Comment

ID: 21840595
>> To Infinity08: What happens for the numbers I want to exclude?

What is it that you want to do exactly ? How many values do you plan to exclude and why ?
0

LVL 3

Expert Comment

ID: 21840609
I don't know any other way of excluding numbers from a random function just replacing them with other numbers.

And.. yes, my random version is a little more time consuming :D
0

LVL 53

Accepted Solution

Infinity08 earned 600 total points
ID: 21840647
If the exclude list is relatively small, you could do something like this (untested) :

``````#include <cstdlib>
#include <ctime>
#include <set>

// calculate a random value between min and max (inclusive), without using the excluded values
int getRandExclude(int min, int max, std::set<int> excludes) {
int value = min + (rand() % (max - min + 1 - excludes.size()));
std::set<int>::const_iterator it;
for (it = excludes.begin(); it != excludes.end(); ++it) {
if (value >= *it) ++value;
else break;
}
return value;
}

int main(void) {
srand(time(0));                            // <--- call this once at the start of the application

std::set<int> excl;                        // <--- list of values to be excluded
excl.insert(5);
excl.insert(100);
excl.insert(50);

int value = getRandExclude(2, 120, excl);  // <--- the random value between 2 and 120 (inclusive) without the excluded values

return 0;
}
``````
0

LVL 5

Assisted Solution

codeQuantum earned 200 total points
ID: 21842495
infinity08 : the problem is that if you exclude a big range, say all values between 25 and 75, you will get either 25 or 75 a lot of the time. The only way to stay statistically precise is to work with only acceptable values from the start.

Well I am not expert in C++, but I am pretty good at algorithms. Here is the algorithm to do what you want, somebody could use that to produce code. The one made by infinity is pretty close...

The idea is pretty simple. You put _only_ valid values in a table, then you pick a random KEY from that table.

Step by step :

(Please note that I talk using arrays, but you probably will have to use sets, vectors, or structures.)

1) Pass an array with all excluded value to your function. Let's call the array excludedValues[]
2) Create a table that will hold valid values... aka the value range minus excludedValues[]. Let's call this table validValues[]
3) Calculate the number of values in the valid values table. Let's call it R. (R is the number of values in the table, not just the size of the table.. using sizeof() won't work correctly as it is the maximum number of values the array can hold and not the actual number of values.)
4) use rand() to pick a value from 0 to R. let's call this K
5) return validValues[K]. This should be the result of the function, the random number we are looking for.

I just tested this using PHP code and the algorithm works perfectly.
0

LVL 53

Expert Comment

ID: 21842503
>> the problem is that if you exclude a big range

As I said in my post :

"If the exclude list is relatively small"

If it's not, then the inverse approach like you explained is of course valid ;)    (assuming that the list of acceptable values is not too big)

It all depends on what Chrysaor intends to use this for - still waiting for his feedback ;)
0

LVL 5

Expert Comment

ID: 21842527
>> If it's not, then the inverse approach like you explained is of course valid ;)    (assuming that the list of acceptable values is not too big)

Why not too big?

I tested with over 10,000 iterations, with a range going from 0 to 9, excluding 1 to 8. The results were either 0 or 9, and over those 10,000 iterations the odds for a 0 or 9 were near 50% (equivalent to flipping a coin). So the algorithm is poven to be mathematically and statistically precise independantly of the size of exclusions and/or inclusions.
0

LVL 53

Expert Comment

ID: 21842535
>> with a range going from 0 to 9, excluding 1 to 8.

That's only a list of 2 acceptable values (0 and 9). That's not a big list ;)

It's just a matter of performance and memory footprint.

Again - all depends on Chrysaor's specific requirements, so I'll wait for those :)
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various â€¦
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilationâ€¦
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
###### Suggested Courses
Course of the Month13 days, 19 hours left to enroll