17
Practice+
1. Create a PL/pgSQL function that returns a string of random
characters of the specified length.
2. The Monty Hall problem.
There are three doors. Behind one of the doors is a prize.
The player selects one of the doors. The game host opens one
of the two remaining doors that does not contain the prize, and
gives the player an opportunity to change the choice — that is,
to select the other door from the remaining two.
Should the player switch the choice, or is it better to stick with
the initial one?
Task: using PL/pgSQL, calculate the probability of winning for
both situations: keeping the initial choice and switching doors.
You can first create the rnd_integer function that returns a random integer
within the specified range. You can use the function for both problems.
For example: rnd_integer(30, 1000) → 616
1. In addition to specifying the string length, you can also provide the list of
allowed characters as an argument. By default, the list can be all Latin
letters, digits, and common special characters. To select random characters
from the list, you can use the rnd_integer function. The function declaration
can look as follows:
CREATE FUNCTION rnd_text(
len int,
list_of_chars text DEFAULT
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789'
) RETURNS text AS ...
Function call example: rnd_text(10) → 'LjdabF_OОJ'
2. You can use an anonymous block for this one.
First, implement one round of the game and see which option won: the initial
one or the modified one. You can use rnd_integer(1,3) for setting and
guessing the winning door.
Then run the game in a loop for a thousand times or so, counting wins for
each strategy. Finally, use RAISE NOTICE to display the counter values and
determine the optimal choice (or lack thereof).