3.2.9 - Random number generation (VB.NET)
Generate values within deliberate bounds and use them in a simple VB.NET simulation. Native code is written without Run; the optional Python demonstration explores repeatable learning tests.
Generating values in a range
A random integer lets a program select a possible outcome without prescribing that outcome in advance.
Dim generator As New Random()
Dim die As Integer = generator.Next(1, 7)
Console.WriteLine(die)
Next(minimum,upperLimit) includes the minimum but excludes the upper limit. The possible results are 1, 2, 3, 4, 5, 6, so the upper argument is 7 for a six-sided die. Next(1,6) could never generate 6. To choose an array index from 0 to names.Length - 1, use generator.Next(0,names.Length).
Create one generator and reuse it rather than making a new object for each draw. A draw's allowed range is predictable; its exact next result is not normally known. AQA supplied RANDOM_INT(1,6) includes both endpoints, so the equivalent native VB.NET call uses Next(1,7). Always check the API's endpoint convention before translating.
For a uniform integer choice, each allowed integer is equally likely. Short runs need not contain every outcome or equal numbers of each. Several repeated values are possible and do not by themselves indicate a fault.
Using random values in a program
A program must connect a random result to the required processing, just as it would process any other value.
To simulate five die rolls and total their scores:
Dim generator As New Random()
Dim total As Integer = 0
For roll As Integer = 1 To 5
Dim die As Integer = generator.Next(1, 7)
total = total + die
Next
Console.WriteLine(total)
The generator call is inside the loop, so each pass gets a new draw. Putting a single draw before the loop would add the same die value five times. The possible total is between 5 and 30 inclusive. If a trace question supplies rolls 6, 2, 2, 1, 4, their total is 15; do not invent new draws during the trace.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account