Solved

# Random?

Posted on 2006-04-12
326 Views
How can I do random from x to y ? From 0 to 20 lets say ?
0
Question by:brightwood

LVL 84

Accepted Solution

x + std::rand() % (y-x+1);
0

Author Comment

mm, im looking for something like

double result = random (min,max)

and then convert result cu CString.

Also, for  std::rand() don't i have to include something ?
0

LVL 84

Expert Comment

#include <cstdlib>
0

LVL 86

Assisted Solution

Adding to ozo's explanation of the basics, you could use

#include <stdlib.h>

#include <time.h>

class Random {

public:

Random() {srand( (unsigned)time( NULL ) );}

double random(double min, double max) const {

double dRand = (double) rand () / (double) RAND_MAX;

double dResult = dRand * (dMax - dMin) + dMin;

return dResult;
}

};

//...

Random r;

double result = r.random (min,max);

You could have that also be

double random(double min, double max) const {

double dRand = (double) rand () / (double) RAND_MAX;

double dResult = dRand * (dMax - dMin) + dMin;

return dResult;
}

//...
double result = random (min,max);

without a class, but you'd have to be sure to seed the random number generator 'manually'.
0

LVL 8

Expert Comment

Also, just to note, if you use #include <iostream> you do not need to include stdlib
0

Expert Comment

I created an own function called rand.
this function can use min and max.
The standard function from the my Borland compiler has only an maximum to use.
Do you want also random values like 3042.492 or so?

//---------------------------------------------------------------------------

#include <vcl.h>
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#pragma hdrstop

double rand(int Min,int Max);

//---------------------------------------------------------------------------

double rand(int Min,int Max) {
int Result;
Result=random(Max);
while(Result <=Min){
Result=random(Max);
}
return Result;
}

#pragma argsused
int main(int argc, char* argv[])
{
double RandomNumber,Min, Max;

cout <<"Random Numbers!:";
cout <<"\nMin";cin >>Min;
cout <<"\nMax";cin >>Max;
randomize();
cout <<"\n\nResults:\n";
for(int i=0;i<20;i++){
RandomNumber=rand(Min,Max);
cout <<"\n"<<RandomNumber;
}
getch();
return 0;
}
//---------------------------------------------------------------------------
0

LVL 1

Assisted Solution

OK, first a function to return a random number in a given range:

Firstly, these require:
#include <time.h>      //used to seed the random-number generator

You'd need the standard library for rand(), but if you're using CStrings, you're using MFC, so you don't need to explicitly #include it.

Now, on to the function!

int random(int min, int max)
{
static bool firstrun=true;      //Is this the first call to this function?
if (firstrun)      //if so...
{
//When called the first time, seeds the random-number
//generator with the current time so that the numbers will
//be different each time you run it.
srand( (unsigned)time( NULL ) );
firstrun=false;      //don't call this again
}
//This looks more complicated than it is.  ^_^
int range = max - min + 1;      //sets the size of your range PLUS ONE (important)
return int(min + ( range * rand() / (RAND_MAX + 1.0) ));
/* The explanation:
The variable "range" is the size of the range you are using.
For example, if min=5 and max=10, range==6 (eg, 10-5+1)

rand() / (RAND_MAX + 1.0) gives you a random value between [0..1)
That is to say, somewhere between 0.0 and up to (but not including) 1.0

When we multiply that by our range, in this case we get a
random value between [0..6)

Lastly, we add our minimum value, leaving us with a final random
value between [5..11)

If we convert this to an int, everything past the decimal point is
chopped off, leaving us      with an integer value between [5..10],
inclusive.  If you DON'T want to convert to int, change the range
so that it does not add one.
*/
}

For doubles, here's the same function (sans comments)

double drandom(double min, double max)
{
static bool firstrun=true;
if (firstrun)
{
srand( (unsigned)time( NULL ) );
firstrun=false;
}
double range = max - min;
return (min + ( range * rand() / (RAND_MAX + 1.0) ));
}

Now, as to converting to a CString, it's super easy.  ^_^

CString has a built-in function called Format, and it works just like printf.

So, given a CString str, to convert an int, just use:

str.Format("%d",blah); where blah is the int.  For example:

str.Format("%d",random(10,20));
(This sets the CString str to an integer value between 10 and 20)

If you would rather use floating random numbers, simply change your format string to reflect that:

str.Format("%.2f",drandom(10,20));
(Sets str to a value between 10 and 20 with two digits of precision)
0

Expert Comment

Applicationmaker wrote:

double rand(int Min,int Max) {
int Result;
Result=random(Max);
while(Result <=Min){
Result=random(Max);
}
return Result;
}

LOL. That is very unoptimalizated funcation. Which school teachs to write like this ?
That's why some applications are really slow...
0

LVL 2

Expert Comment

[QUOTE]
Applicationmaker wrote:

double rand(int Min,int Max) {
int Result;
Result=random(Max);
while(Result <=Min){
Result=random(Max);
}
return Result;
}

LOL. That is very unoptimalizated funcation. Which school teachs to write like this ?
That's why some applications are really slow...
[/QUOTE]

let's try this function
rand(99999,100000);
see how many long the while loop runs
0

LVL 1

Expert Comment

I have an objection.  Neither ozo's nor jkr's comments explain anything, nor do they completely answer the author's questions.  Mine was the only post to answer (and explain the why and how) the random range function and the conversion to cstring.  If you have to split, split between me and jkr.
0

LVL 20

Expert Comment

The original question is how to geneate a random number and both answers answer it fully
0

LVL 1

Expert Comment

Humbly, I disagree.  As I understood it, our role is to guide and teach, not write functions to fit specifications.

I do not disagree that both ozo and jkr provided code that could generate the specific random numbers.  However, neither provided explanations explaining how their code works, and neither addressed the author's additional request regarding cstrings.

As someone with administrative powers, you also have a great responsibility, to both the authors and the experts.  Truly, it was the author's responsibility to choose whichever answer best fit their needs, and if brightwood had chosen ozo's or jkr's answers, I would have said nothing.  But, brightwood has not returned, and if it is up to you to cleanup this question, I would ask that you choose the most complete answer, not simply the first.  Indeed, the author's single comment would seem to indicate that ozo's answer, at least, was not satisfactory.
0

LVL 8

Expert Comment

I disagree with pcgabe about the idea of giving him points based on explanation.  I think the only one that can
pcgabe is the only one who helped with that and for that, I believe he should be cut in on the split.  I think that
since he is the only one whom responded to that part of the question at all, if the asker had not left, the asker
would have rewarded him points in the split.
0

## Featured Post

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.