Home > ASP > Generating Random Number in ASP

Generating Random Number in ASP

September 20th, 2009 Captain Leave a comment Go to comments

Generating random numbers is very important in programming. We have to use random numbers to show a random record (Image, Saying, Article etc.) on our pages. Also, we can use random numbers for everything that we can imagine. In this article, we will see easiness of generating random numbers with ASP.


Structure 1.0:

1
2
3
4
<%
randomize
response.write int(rnd*MaxNumber)
%>

Formula: 0 <= result < MaxNumber
At line 2, randomize statement is used to generate a different number for each time we call the rnd() function.

At line 3, a random number was generated between 0 and MaxNumber variable but except the MaxNumber’s value, was converted integer with int() function and was printed. Let’s make an example.

Example 1.0: This usage gives us a random number between 0 and 100 but except 100. Minimum value of generated number can be 0 and maximum value of generated number can be 99, can not be 100.

1
2
3
4
5
6
<%
randomize
response.write int(rnd*100)
'if we want to generate a random number inculding 100,
'We need to use this code : int(rnd*101) or round(rnd*100)
%>

Probable Output of Example 1.0:

1
78

1.1) Generating a Random Number Between Two Numbers

Structure 1.1: If we want to generate a random number between two numbers (that we determined), we should define a StartValue variable. We can make it like this:

1
2
3
4
<%
randomize
response.write int(rnd*(MaxNumber-StartValue))+StartValue
%>

Formula: StartValue <= result < MaxNumber

Example 1.1: With this usage, a random number is generated between 1000 and 2000 but except 2000.

1
2
3
4
5
6
<%
randomize
StartValue=1000
Maximum=2000-StartValue
response.write int(rnd*Maximum)+StartValue
%>

1.2) Getting a Random Element from a Collection

Example 1.2: Assume that we need to get a random item from an array.

1
2
3
4
5
6
<%
my_array=Array("ASP","PHP","JAVASCRIPT","AJAX","CSS","JQUERY")
randomize
response.write my_array(int(rnd*6))
'Generated a random number which is maximum 5 and minimum 0.
%>

Let’s improve our example…


Example 1.3: This time, we going to get multiple items from an array.

1
2
3
4
5
6
7
8
9
<%
my_array=Array("ASP","PHP","JAVASCRIPT","AJAX","CSS","JQUERY")
randomize
repetition=int(rnd*5)+1
for i = 0 to repetition
response.write "I am learning "&my_array(int(rnd*6))
response.write " on Memiso.com<br />"
next
%>

Probable Output of Example 1.3:

1
2
3
4
I am learning AJAX on Memiso.com
I am learning ASP on Memiso.com
I am learning PHP on Memiso.com
I am learning ASP on Memiso.com

A Little Homework For You

As you see, it is possible getting duplicate elements. So, try to make an application that gets every single element from array only once.

Bookmark and Share
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker