Random Numbers and ASP

by Stephen Lian


Have you ever wanted to create a webpage that is dynamic and ever changing? In this article, I will show you how to use VBScript's Randomize and Rnd functions in ASP to generate near random numbers that can be used to create dynamic effects and content.

To begin, let's review the Rnd and Randomize functions, which are at the core of random numbers in ASP. The Rnd function produces a fractional number between zero and one. The way in which it generates the fraction depends on a complex formula and a starting number or seed. Without having a different starting number each time it is called, Rnd returns the same fractional number, which is obviously not the desired effect. So here is where the Randomize function comes into the mix. Randomize makes use of the computer's system clock to provide a different seed to Rnd on each occasion. So combining Rnd with Randomize enables Rnd to effectively produce a random fractional number.

For example, set up an ASP page with the following code, load it, and then refresh your browser several times to see how the number written is different each time the page loads:


<%
Dim RandomFractionalNumber
Randomize
RandomFractionalNumber = Rnd
Response.Write(RandomFractionalNumber)
%>

By the way, the number produced is not actually "random" as random is meant in strict mathematical parlance, but instead is a simulation of a random number, which for all intents and purposes is good enough.

Having described how Randomize and Rnd works, I'll now briefly show how to use them in an application. As a fractional number, the output from Rnd is not very useful. So, here you'll have to create a function that will convert the fractional number into something that can be used, such as an integer between one and X. To generate a random integer between one and X, multiply the fraction produced by Rnd by an integer X and convert the result into an integer (using VBScript's Int function which simply discards the fractional part of a number) and then add one to the result.

Try the following code, which simulates the rolling of a die, as an example:


<%
Function RandomNumber(intHighestNumber)
	Randomize
	RandomNumber = Int(Rnd * intHighestNumber) + 1
End Function

Response.Write(RandomNumber(6))
%>

Naturally, it is possible to create variations of this function to produce different kinds of near random numbers such as a random number between the integers Y and Z. How your function reads and works depends on what you would like to accomplish.

Once you have a random integer, you basically have a means to create on the Web all kinds of dynamic effects and content, games and puzzles, experiments, and the like. What I will show you in the remainder of this article is two examples of how random numbers can be used in ASP to produce an ever changing page.

The first example is a tip of the day page. Many a desktop application has a random tip of the day to help users become acquainted with it. With random numbers and ASP, a tip of the day can easily be added to your Web application.

For the sake of this example, let's say you have ten tips and you would like to display a tip randomly each time the tips page loads. To set up the "database" of tips, you can use a VBScript array within the ASP page, a text file with each line representing a different tip, or a relational database such as Access or SQL Server with each tip stored as a record in a table. If you were to use a relational database, then you should be careful to ensure that the field in the table of records that identifies each record does not have any missing numbers; otherwise a select query like the following might not yield the desired effect:

"SELECT fldTip FROM tblTips WHERE fldTipID = " & intRandomNumber & ";"

For the purpose of this article, I will describe how to set up the random tip generator using an array, but of course the concept is largely the same irrespective of where the data is stored.

The first thing to do is to ensure that your page will not be cached by the client's browser or by a proxy server. The reason for this is that the content of the page should always be fresh if the tip generator is to work properly. Next, set up the database of tips. By using an array to store the tips, this part is just a matter of dimensioning an array and setting each element of the array to hold a different tip. Having done that, establish a random number function to produce a random number between one and ten. Then dimension a string variable, set the variable to equal the ith element of the array, where i is the random number between one and ten. Finally, in the HTML part of the page, print out the contents of this variable. The result is a "random" tip of the day.


<%
Option Explicit
Response.Buffer = True

'For browsers (set expiration date some time well in the past)
Response.Expires = -1000


'For HTTP/1.1 based proxy servers
Response.CacheControl = "no-cache"

'For HTTP/1.0 based proxy servers
Response.AddHeader "Pragma", "no-cache"

Dim Tip(10)

Tip(1)  = "This is tip 1"

Tip(2)  = "This is tip 2"
Tip(3)  = "This is tip 3"
Tip(4)  = "This is tip 4"
Tip(5)  = "This is tip 5"
Tip(6)  = "This is tip 6"
Tip(7)  = "This is tip 7"

Tip(8)  = "This is tip 8"
Tip(9)  = "This is tip 9"
Tip(10) = "This is tip 10"

Function RandomNumber(intHighestNumber)
	Randomize
	RandomNumber = Int(intHighestNumber * Rnd) + 1
End Function

Dim strRandomTip
strRandomTip = Tip(RandomNumber(10))
%>
<html>
<head>
  <title>Random Tip Example</title>
</head>

<body>
  <div style="border:thin solid black;margin:1em;
    padding:1em;height:100px;width:100%">

    <h1>Tip of the Day</h1>
    <p><%= strRandomTip %><p>

  </div>
  <br />

  <form name="frmNewTip">

  <input type="button" name="cmdNewTip" value="Another Tip"
    onClick="window.open(document.location.href,'_top');" />

  </form>
</body>
</html>
<% Response.End %>

Aside from dynamic, random content, random numbers can also be used to produce dynamic, random effects.

One example of a random effect is a page that randomly changes its background colour each time it loads.

To achieve this, set up an array of colours in the same fashion as the array of tips. Then, again in the same way as before, generate a random number to serve as the current index of the array.

Coupled with an innovative page design, this concept can produce an impressive site!


<%
'...
'same caching control code as above

Dim Colour(5)

Colour(1) = "blue"
Colour(2) = "red"
Colour(3) = "yellow"

Colour(4) = "green"
Colour(5) = "gray"

Function RandomNumber(intHighestNumber)
	Randomize
	RandomNumber = Int(intHighestNumber * Rnd) + 1
End Function

Dim strRandomColour
strRandomColour = Colour(RandomNumber(5))

%>
<html>
<head>
  <title>Random Color Example</title>
  <style type="text/css">

    BODY {background-color: <%= strRandomColour %>;}
  </style>
</head>
<body>
  <p>

  Refresh this page with CTRL-R or F5 and notice
  that its background colour changes randomly.
  </p>
</body>
</html>
<% Response.End %>

In conclusion, random numbers can be used in ASP to produce all kinds of wonderful, dynamic effects. www.database-applications.net is one Web application that uses random numbers and ASP in interesting ways. With random numbers, your Web application is limited only by your imagination.


Author Profile

Stephen Lian is a Web application developer in Australia, specialising in Microsoft solutions. He is the creator of www.database-applications.net, a global IT services marketplace, a knowledge base of Microsoft technologies, and a directory of software and Web sites.



About the Author

From ASP101

Articles originally posted on ASP101.com

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds