Random integers

Gluttard

Active member
Joined
Jan 9, 2008
Messages
44
Programming Experience
Beginner
I don't quite understand the 'random' class, so could someone give me the code to produce a random integer between 1 and 10?
If you could explain it then that would be great too. Thanks!
 
Random numbers in the computer world aren't technically "Random".
Most random functions will take the current CPU time, or clock cycle and run a bunch of calculations against that to get a seemingly random number.

The simplest way to get a "Random" number between one and ten:

VB.NET:
Dim MyRandomNumber as Integer = (Int(Rnd(1) * 10) + 1)

This may give you weird results. Try putting this in a simple form with a button click and text box. Run it and remember the numbers it produces. Then run it again. It should produce the same "Random" numbers over and over, each time the program is run.

The Random class will take this function one step further, by accepting an integer value called a Seed. The seed is then run against various calculations to produce a slightly more "Random" number. Try this:

VB.NET:
Dim r As New Random(Int(Format(Now, "fffff")))
Dim MyRandomNumber as Integer = r.Next

Each time this is run it will take the specific sub seconds of the CPU clock and use it as the seed. Your numbers will appear more "Random"

If security is your concern then you might want to try this:

VB.NET:
 Dim r As System.Security.Cryptography.RandomNumberGenerator = _
         System.Security.Cryptography.RandomNumberGenerator.Create()
 Dim by(1) As Byte
 r.GetBytes(by)
 Dim MyRandomNumber as Integer = Int(by(0))

This is a little more involved. The RandomNumberGenerator will actually use the same principals as above, but with the added security of a hashing algorithm. The length of the input byte array will determine the output.
Since your only interested in numbers 1-10 you can "MOD 10" the above function.

Hope this helps.
 
Last edited by a moderator:
I don't quite understand the 'random' class, so could someone give me the code to produce a random integer between 1 and 10?
If you could explain it then that would be great too. Thanks!
It requires no explanation as it's so simple:
VB.NET:
Dim myRandom As New Random
Dim myInteger As Integer = myRandom.Next(1, 10 + 1)
 
Back
Top