Solved

Random numbers from a specific range in C++

Posted on 2008-06-22
10
3,092 Views
Last Modified: 2008-06-26
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
Comment
Question by:Chrysaor
  • 5
  • 2
  • 2
  • +1
10 Comments
 
LVL 3

Assisted Solution

by:sistemu
sistemu earned 100 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;

}

Open in new window

0
 
LVL 53

Expert Comment

by:Infinity08
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;

}

Open in new window

0
 

Author Comment

by:Chrysaor
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

by:Infinity08
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

by:sistemu
ID: 21840609
I don't know any other way of excluding numbers from a random function just replacing them with other numbers.
I can't help you without further knowledge of the circumstances.

And.. yes, my random version is a little more time consuming :D
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 53

Accepted Solution

by:
Infinity08 earned 150 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;

}

Open in new window

0
 
LVL 5

Assisted Solution

by:codeQuantum
codeQuantum earned 50 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

by:Infinity08
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

by:codeQuantum
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

by:Infinity08
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
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.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now