Solved

Random numbers from a specific range in C++

Posted on 2008-06-22
10
3,115 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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
 
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Question of running the program built from sample in codeproject website 3 70
FMX TCameraComponent Problem 2 69
max float value 3 41
Advice in Xamarin 21 79
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

770 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