3.2.9 - Random number generation (C#)

3.2.9 - Random number generation (C#)

Generate values within a specified range and use each generated result consistently in a program. Required written answers use C#; native execution is unavailable here, with an optional Python demonstration.

Generating values in a range

Random number generation supplies varying values for applications such as a die roll, game target or selection from a collection.

C#
Random generator = new Random();
int die = generator.Next(1, 7);

Create the generator once, then call it when a new result is needed. In C#, Next(lower, upper) includes the lower bound but excludes the upper bound. The example can produce 1, 2, 3, 4, 5 or 6. Next(1, 6) would miss face 6; Next(0, 6) would include an unwanted 0.

For a target between 10 and 20 inclusive, use Next(10, 21). For an index into an array of length 6, use Next(0, 6). Decide the permitted values first and then translate to the native API's endpoint rule. AQA RANDOM_INT(1, 6) includes both endpoints; its upper argument therefore differs from C#.

You need to use random values within programs, but do not need to explain how a pseudo-random generator produces them internally. A small sample also need not contain every allowed value; absence from one run does not prove a boundary is excluded.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account