Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

random number generation

Hi,
Can I please get a C code for generating  a random number that is uniformly distributed in the range[8,32].
Thanks.
0
bujji71
Asked:
bujji71
1 Solution
 
GulaCommented:
if I understood right, then

rand()%25 + 8;
0
 
luisseixasCommented:
I don't know about C but, check this Delphi code out. Maybe you can get some ideas.

First, somewhere in your project, you start then built-in random number generator:


procedure TForm1.FormCreate(Sender: TObject);
begin
  Randomize;
end;


The "Random" function gives you a number 0 <= N < 1. Just do something like this:


procedure TForm1.ButtonClick(Sender: TObject);
const Upper=32;
      Lower=8;
var   Number: Integer;
begin
  Number:=Trunc(Random*(Upper-Lower+1))+Lower;
end;


Easy!
0
 
Leo71Commented:
For Windows, MS VC I would suggest:

#include <stdlib.h>
#include <time.h>

   /* Seed the random-number generator with current time so that
    * the numbers will be different every time we run.
    */
   srand( (unsigned)time( NULL ) );

   (rand()*(32-8))/RAND_MAX+8;

srand with time is because otherwise you programm starts everytime with the same sequence of random numbers.

If you search for a code to implement you own random numbe generator I can't help you.

Regards
Leo
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!

 
d34thkCommented:
mmhmm...

use

srand(time(NULL));
rand()%x+y;

i cant remember how the x and y works, but if u work it out, it makes the random number be between them.

i think the minimum random number is x, while the maximum is x+y (add them together)

so 1+2 would give u a random number between 1 and 3

correct me if im wrong
0
 
Leo71Commented:
you mean srand()%(32-8 +1)+8, I guess :), like Gula said.

With other words: srand()%(Range+1)+startvalue
which works as long fine, as Range < RAND_MAX.

My solution ((rand()*Range)/RAND_MAX+startvalue can blow up the values over RAND_MAX, but the resolution still sticks at RAND_MAX.
But one could multiply two random numbers, if a higher range+resolution is needed.... ;-).

Regards
Leo
0
 
CleanupPingCommented:
bujji71:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

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!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now