?
Solved

Random?

Posted on 2006-04-12
15
Medium Priority
?
334 Views
Last Modified: 2010-04-01
How can I do random from x to y ? From 0 to 20 lets say ?
0
Comment
Question by:brightwood
  • 3
  • 2
  • 2
  • +6
13 Comments
 
LVL 85

Accepted Solution

by:
ozo earned 672 total points
ID: 16441876
x + std::rand() % (y-x+1);
0
 

Author Comment

by:brightwood
ID: 16442107
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 85

Expert Comment

by:ozo
ID: 16442124
#include <cstdlib>
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Assisted Solution

by:jkr
jkr earned 664 total points
ID: 16442152
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

by:List244
ID: 16447315
Also, just to note, if you use #include <iostream> you do not need to include stdlib
0
 

Expert Comment

by:Applicationmaker
ID: 16448977
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

by:pcgabe
pcgabe earned 664 total points
ID: 16460418
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

by:PaneQ
ID: 16465534
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

by:seet82
ID: 16466883
[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

by:pcgabe
ID: 16706825
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

by:Venabili
ID: 16706894
The original question is how to geneate a random number and both answers answer it fully
0
 
LVL 1

Expert Comment

by:pcgabe
ID: 16707028
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

by:List244
ID: 16709512
I disagree with pcgabe about the idea of giving him points based on explanation.  I think the only one that can
determine if that was helpful is the asker.  However, the asker did ask also, how to get that value into a CString.
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

755 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