Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Random number within a range

Generating a random number in C++ is easy, but for generating one within a range you must use a little trick.

On Tuesday, March 16th 2004 at 06:53 PM
By Andrew Pociu (View Profile)
***--   (Rated 2.2 with 13 votes)
Contextual Ads
More C++ Resources
Advertisement

First, let’s see the script and then we shall analyze it.


// Generating a random number within a range

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
    srand(GetTickCount());
    int i = rand()%10;
    cout << i;
    return 0;
}



#include <windows.h>

- we must include ‘windows.h’ because we use GetTickCount().


srand(GetTickCount());

- it retrieves the number of milliseconds elapsed since the system start. This is the trick for getting a random number. If we don’t use this function, we will get a random number, but the same number all the time. This is the way a computer creates a random number… the time.

 int i = rand()%11; - this is the trick we use to get the number within a given range. We use the modulus operator to get the rest of the division of the number by eleven (because if we used %10 and the random number would be 10, 10%10 = 0).
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Ernest Pazera on Wednesday, March 17th 2004 at 07:12 PM

The proper form:

n=(rand()%(max-min+1))+min;

by benny feathers on Friday, April 30th 2004 at 06:36 AM

#include <ctime>
srand ( time (0) ); //uses system time to randomize

by guzz on Thursday, March 24th 2005 at 03:35 PM

Unfortunately this trick to set the range is a poor one: most C library random number generators are not very good! The lower bits of the generated numbers are not that random, so using modulus gives not particularly random results. (e.g. rand() % 2 may produce 0,1,0,1,0,1,0,1,... on some systems). It would be fine if the standard C random generator was high quality, but most of the time it sucks. A better way (for small integer values) is to use:
rand() / (RAND_MAX / N + 1).

by RG on Tuesday, August 9th 2005 at 06:00 PM

While not in C++ What I have found to generate great random values is to take raw system time as part of the algorythm.

ie:

((timer*rnd) mod (1.15*100) +1) *.01

This will generate very random values between .01 and 1.15

it can be modified to suit any ranges

by rg on Tuesday, August 9th 2005 at 06:07 PM

Ooops... Hit the wrong button.

Again

(timer*rnd) mod (1.15*100) +1) *.01

Where timer = a system timer value (in visual basic the Timer statement return the number of seconds since midnight)

1.15 represents your "high range" which for this example is mulltiplied by 100 to make the single into a integer value (ie: if you had 1.711 then multiply by 1000 instead of 100)

+1 ensures no zero value

multiplied by .01 brings the resultant value back into a single precision value.

Again, by simply manipulating the various values you can create whatever range of values required and it is quite random in result.

by on Thursday, July 13th 2006 at 06:21 AM

i am using linux so is windows.h is in linux c

by Andrei Pociu on Thursday, July 13th 2006 at 11:20 AM

As far as I know, windows.h is a Microsoft Windows specific file, so you will need to use a different method that applies to your operating system.

by quoccuong on Friday, March 9th 2007 at 12:08 AM

================================
i am using linux so is windows.h is in linux c
================================

To implement the GetTickCount API when porting code from Windows to Linux, use the following code:

long getTickCount()
{
tms tm;
return times(&tm);
}

by nolizwi mhambi on Friday, April 20th 2007 at 06:21 AM

windows application when the next button is clicked the random number between 1 and 12 are generated and displayed in the boxed label.the user the guesses the answr types it into the text box and either clicks the mark button or enter button .the typed answer is compared to the calculated answer and verdict is displayed in the bottom label.if the answer was incorrect the user still has more attempt to guess the correct answer

by michael on Saturday, June 9th 2007 at 01:42 PM

This code is not protable. it's better to use standard C time functions to improve its portability. Why not protable code is allowed here anyway?

by Andrei Pociu on Saturday, June 9th 2007 at 04:14 PM

Portable code is allowed.

by paul on Friday, October 12th 2007 at 10:29 PM

how do I prevent repetition of an integer?

by Ale on Friday, November 30th 2007 at 08:35 PM

do any of you know how to randomize a number in assembler??

by Drw on Tuesday, March 4th 2008 at 01:00 PM

The method of Guzz

rand() / (RAND_MAX / N + 1)

will give ever so slightly less occurrences for the top number returned, given the integer math.

Say N is 23, and RAND_MAX is 65535. RAND_MAX / N + 1 is 2850. So when rand() returns anything from 0 to 2849, the formula gives 0 - from 2850 through 5699 gives 1, etc. The values that would give an equal chance of returning 22 would be the range from 62700 - 65549 - but rand() never returns anything from 65536 through 65549. There are 14 less points, so there is 14/2850 less chance of getting 22 vs all the other numbers.

If modulo doesn\'t work - and I can see the validity of that claim - I think it needs to be
float(rand()/RAND_MAX) * N , to return 0 through N.

by Drw on Monday, March 10th 2008 at 11:48 AM

After some more thot: I realize the formula I gave (with bad syntax, besides) will only return N for one value - when rand() returns RAND_MAX. Which isn't good.

I switched to using
((float)rand()/(RAND_MAX+1)) * N
to return values between 0 and N-1 .
which has one more data point to return 0 - but it's the best I can think of.

by RAMAR on Tuesday, July 29th 2008 at 06:36 AM

how to generate the two dymensional random number whoes radius is with in length l.
exanples
sqrt(X(i)^2 Y(i)^2 )<=l

R.RAMAR
SOC
IGCAR
india

by aislinn on Tuesday, September 2nd 2008 at 08:30 PM

hi!..,
just wanna ask if you do know how to use random thing using SQL? not the mySQL, its the SQL(stacks, queues, list)?????

HELP ME PLEASE......

by aislinn on Tuesday, September 2nd 2008 at 10:23 PM

how to generate a random number that if you run the program and press enter, you will have a number then press a button then a random number again...??????, it won't go back to the program (or to your code)..

by szagory on Saturday, February 21st 2009 at 03:27 PM

Drv's formula is more or less what appears in MSDN library ((MSDN's version doesn't have his correction for N):

(((double) rand() / RAND_MAX) * RANGE_MAX RANGE_MIN);

Neither formula produces correct results. Below is the code to generate random value within the given range (1 ... 51), with the lower boundary sliding up and the range progressively shrinking to 2...51, 3...51 and so on to 50...51 (I've been playing with some deck-shuffling ideas):

const int NUM_CARDS = 52;
srand((unsigned) time(NULL));

for (int i = 0; i < NUM_CARDS - 1; i )
{
int minRange = i 1;
int maxRange = NUM_CARDS - 1;
int newIndex = (int) (((double) rand() / RAND_MAX) * maxRange minRange);
//int newIndex = (int) (((double) rand() / (RAND_MAX 1)) * (maxRange 1) minRange);
printf("Index %d -> Range [%d ... %d] -> %d\n", i, minRange, maxRange, newIndex);
}

MSDN's formula (used in the code above) generates this output (Microsoft Visual Studio 2005 on Windows XP):

Index 0 -> Range [1 ... 51] -> 2
Index 1 -> Range [2 ... 51] -> 2
Index 2 -> Range [3 ... 51] -> 35
Index 3 -> Range [4 ... 51] -> 42
Index 4 -> Range [5 ... 51] -> 12
Index 5 -> Range [6 ... 51] -> 12
Index 6 -> Range [7 ... 51] -> 57
Index 7 -> Range [8 ... 51] -> 48
Index 8 -> Range [9 ... 51] -> 17
Index 9 -> Range [10 ... 51] -> 23
Index 10 -> Range [11 ... 51] -> 59
Index 11 -> Range [12 ... 51] -> 36
Index 12 -> Range [13 ... 51] -> 23
Index 13 -> Range [14 ... 51] -> 22
Index 14 -> Range [15 ... 51] -> 63
Index 15 -> Range [16 ... 51] -> 23
Index 16 -> Range [17 ... 51] -> 17
Index 17 -> Range [18 ... 51] -> 24
Index 18 -> Range [19 ... 51] -> 64
Index 19 -> Range [20 ... 51] -> 23
Index 20 -> Range [21 ... 51] -> 23
Index 21 -> Range [22 ... 51] -> 72
Index 22 -> Range [23 ... 51] -> 68
Index 23 -> Range [24 ... 51] -> 51
Index 24 -> Range [25 ... 51] -> 41
Index 25 -> Range [26 ... 51] -> 74
Index 26 -> Range [27 ... 51] -> 53
Index 27 -> Range [28 ... 51] -> 30
Index 28 -> Range [29 ... 51] -> 33
Index 29 -> Range [30 ... 51] -> 41
Index 30 -> Range [31 ... 51] -> 41
Index 31 -> Range [32 ... 51] -> 50
Index 32 -> Range [33 ... 51] -> 62
Index 33 -> Range [34 ... 51] -> 60
Index 34 -> Range [35 ... 51] -> 70
Index 35 -> Range [36 ... 51] -> 41
Index 36 -> Range [37 ... 51] -> 59
Index 37 -> Range [38 ... 51] -> 45
Index 38 -> Range [39 ... 51] -> 51
Index 39 -> Range [40 ... 51] -> 69
Index 40 -> Range [41 ... 51] -> 64
Index 41 -> Range [42 ... 51] -> 75
Index 42 -> Range [43 ... 51] -> 61
Index 43 -> Range [44 ... 51] -> 59
Index 44 -> Range [45 ... 51] -> 49
Index 45 -> Range [46 ... 51] -> 95
Index 46 -> Range [47 ... 51] -> 93
Index 47 -> Range [48 ... 51] -> 55
Index 48 -> Range [49 ... 51] -> 99
Index 49 -> Range [50 ... 51] -> 95
Index 50 -> Range [51 ... 51] -> 71

Drv's formula (commented out in the snippet above) gives the following :
Index 0 -> Range [1 ... 51] -> 4
Index 1 -> Range [2 ... 51] -> 33
Index 2 -> Range [3 ... 51] -> 26
Index 3 -> Range [4 ... 51] -> 36
Index 4 -> Range [5 ... 51] -> 25
Index 5 -> Range [6 ... 51] -> 28
Index 6 -> Range [7 ... 51] -> 14
Index 7 -> Range [8 ... 51] -> 33
Index 8 -> Range [9 ... 51] -> 32
Index 9 -> Range [10 ... 51] -> 47
Index 10 -> Range [11 ... 51] -> 35
Index 11 -> Range [12 ... 51] -> 60
Index 12 -> Range [13 ... 51] -> 55
Index 13 -> Range [14 ... 51] -> 54
Index 14 -> Range [15 ... 51] -> 19
Index 15 -> Range [16 ... 51] -> 52
Index 16 -> Range [17 ... 51] -> 40
Index 17 -> Range [18 ... 51] -> 46
Index 18 -> Range [19 ... 51] -> 30
Index 19 -> Range [20 ... 51] -> 48
Index 20 -> Range [21 ... 51] -> 37
Index 21 -> Range [22 ... 51] -> 71
Index 22 -> Range [23 ... 51] -> 33
Index 23 -> Range [24 ... 51] -> 63
Index 24 -> Range [25 ... 51] -> 50
Index 25 -> Range [26 ... 51] -> 59
Index 26 -> Range [27 ... 51] -> 69
Index 27 -> Range [28 ... 51] -> 78
Index 28 -> Range [29 ... 51] -> 35
Index 29 -> Range [30 ... 51] -> 44
Index 30 -> Range [31 ... 51] -> 43
Index 31 -> Range [32 ... 51] -> 80
Index 32 -> Range [33 ... 51] -> 33
Index 33 -> Range [34 ... 51] -> 84
Index 34 -> Range [35 ... 51] -> 44
Index 35 -> Range [36 ... 51] -> 80
Index 36 -> Range [37 ... 51] -> 37
Index 37 -> Range [38 ... 51] -> 43
Index 38 -> Range [39 ... 51] -> 42
Index 39 -> Range [40 ... 51] -> 88
Index 40 -> Range [41 ... 51] -> 49
Index 41 -> Range [42 ... 51] -> 49
Index 42 -> Range [43 ... 51] -> 63
Index 43 -> Range [44 ... 51] -> 90
Index 44 -> Range [45 ... 51] -> 82
Index 45 -> Range [46 ... 51] -> 77
Index 46 -> Range [47 ... 51] -> 59
Index 47 -> Range [48 ... 51] -> 96
Index 48 -> Range [49 ... 51] -> 97
Index 49 -> Range [50 ... 51] -> 92
Index 50 -> Range [51 ... 51] -> 90

Evidently, the random number generated is acceptable when the range is sufficiently wide - but, as the range narrows, the generated values escape the range's boundaries.
Another thing worth mentioning is that both formulas repeatedly produce the same starting value (for index 0 in the range 1...51) on successive runs - value of, say, 7 is returned for a minute or so.
Would be glad to hear suggestions from Drv or others, more mathematically minded than myself.

SZ

by szagory on Saturday, February 21st 2009 at 03:36 PM

Just a small note - don't know what happened to all my pluses in the posting above, they seem just to have been stripped when my posting makes it onto the page. You can see it in the code snippet, "i " was transformed to "i " and so on. A bit confusing - especially as I don't know how to stop this from happening...

by Anon on Wednesday, May 20th 2009 at 05:42 PM

double range = 0.5;

double random_num = (rand() % int(range*1000) - range*1000/2)/1000.0;


The trick is to move the decimal of range so you can make it an int for the % then after you can move the decimal back..

by Jack Sparrow II on Thursday, August 5th 2010 at 11:09 AM

My question is how do I generate all the numbers between 1 and 54 in a random order without generating the same one multiple times?


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C++ Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources