Padding Padding
Janet
Systems
 Register  Login 
Telephone  01628 566 178
Website Design, Hosting and Software Services
  Search 
Padding
corner Padding corner
Padding Padding
corner Padding corner
 ASP.NET Articles

Creating random numbers in ASP.NET, initially with the rnd function, then some suggestions for refinement.

In ASP.NET when we wish to create a random number we can use the Rnd function. This function will return a random decimal number between 0 and 1. Therefore if we wish to select one of 5 items, say, we need to multiply this value by the number of items available. For example:

Dim colours(11)
 colours(0) = "red"
colours(1) = "blue"
colours(2) = "green"
colours(3) = "magenta"
colours(4) = "gold"
colours(5) = "purple"

textBrush = New SolidBrush(System.Drawing.ColorTranslator.FromHtml(colours(Int(Rnd() * 5))))
textFont = New Font("Verdana", 10)< BR > grph.DrawString(str, textFont, textBrush, 20, 15)

In this example we are creating an array of colours. We then pick one of these colours to assign to our brush. Note our 5 multiplier and int converter to take our random number to an integer between 0 and 5.

As an alternative to using int, which chops the decimal number to produce the desired integer, you may wish to consider using the function round, which will produce a more balanced result.

One of the problems with the above approach is the starting point for the random number sequence. A sequence of random numbers generated by a computer is only pseudo random. As a consequence starting the sequence under the same circumstances will result in the gneration of the same sequence of numbers. To overcome this problem we can seed our number generation, getting it to start t a different point in the series. One of the common ways of generating a seed for a random number generator is to take the current date and time. In our example below we are creating a string of 4 random letters.

Dim i as integer
Dim RandomNum As New Random(Now.Millisecond)
For i = 0 To 4
   str = str + Chr(RandomNum.Next(65, 90))
Next i

As can be seen in our example above, we are using the current time in milliseconds as a seed for our random number generator. Also illustrated in the above example is the option of speciying the random number to be between two given integers. In this case between 65 and 90 the ASCII values for A and Z.

NAT January 2006


This article viewed: 733 times Back

Copyright © 2004-2007 Janet Systems Ltd.

 Print   

DotNetNuke Website design and hosting from £15.00 per month. More...

Looking for a website design company in the Thames Valley, call us on 01628 566178

DotNetNuke Modules
DotNetNuke Modules availalble from Janet Systems

DotNetNuke Skins
DotNetNukeSkins.gif

from Janet Systems

Padding
Copyright 2002-2008 Janet Systems Ltd.   Terms Of Use  Privacy Statement Tuesday, May 13, 2008