Random number generation

In the previous chapter, we learned about the Random feature and its usage options when drawing randomly sized shapes into random positions. The Random function can be used also for generating random numbers.

Often you need to select a random number for different test programs or games (from simpler to the more complex). In most programming languages, there is similar random number generation function - Random.

The Random function can be used in two ways:

1. To generate a random rational number

When selecting a random rational number, it is written in brackets as parameter upper limit (Figure 47). 

Figure 47: Randomly generated rational number
Figure 47: Randomly generated rational number

In our case, we will choose the upper limit number 10, and therefore our program after (re)running always generates a random number from 0 (inclusive) to 9 (always 1-point smaller number than indicated in brackets).

In the example, we used the new IntToStr command (Integer to String - literally we can translate as a change of an integer to a character string). This command is called a conversion - change of the type by which the TextOut command can read numerical values. In the next example we will also use the conversion but we will change the real (decimal) number to the string character - FloatToStr.

2. To generate a random decimal number

When selecting a random decimal number into brackets, we do not write any parameter (Figure 48). 

Figure 48: Randomly generated decimal number
Figure 48: Randomly generated decimal number

This example generates a random decimal number that is larger or equal 0 and smaller than 1. 

In order to be able to work with a randomly generated number, you need to save it to variable (Figure 49). 

Figure 49: Assigning of randomly generated number to a variable
Figure 49: Assigning of randomly generated number to a variable

In many cases, we will not want the program to generate random numbers from 0, so we will add the bottom limit of the numbers we want to generate (Figure 50). 

Figure 50: Random number generation at a given interval
Figure 50: Random number generation at a given interval

If you want to run a program that contains Random function multiple times, the numbers will be generated randomly, but they will be the same at each run. These are basically the numbers selected from a random number table, if you want to change the table, it is necessary to use the Randomize command (Figure 51) that ensures complete "random number mixture". 

Figure 51: Randomize command
Figure 51: Randomize command
Vytvorte si webové stránky zdarma! Táto stránka bola vytvorená pomocou služby Webnode. Vytvorte si vlastný web zdarma ešte dnes! Vytvoriť stránky