17
Practice
1. Create a PL/pgSQL function that returns a string of random
characters of the specified length.
2. A shell game problem.
One of the three shells contains a pea.
A player selects one of the shells. The operator removes one of
the two remaining shells (which must be empty) and gives the
player an opportunity to change the choice, i.e., select the other
shell from the remaining two.
Does it make sense to change the choice, or is it better to keep
the initial one?
Assignment: using PL/pgSQL, estimate the probability of the
win for both the first and second choices.
You can first create the rnd_integer function that returns a random
integer within the specified range. This function will be useful for solving
both problems.
For example: rnd_integer(30, 1000) → 616
Task 1. Apart from the string length, you can also provide the list of allowed
characters as an input parameter. By default, it can be all alphabetic
characters, digits, and some other special characters. To select random
characters from the list, you can use the rnd_integer function. A function
declaration can look as follows:
CREATE FUNCTION rnd_text(
len int,
list_of_chars text DEFAULT
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789'
) RETURNS text AS ...
An example of the function call: rnd_text(10) → 'LjdabF_OОJ'
Task 2. You can use an anonymous block in your solution.
First, you have to develop an individual game run and check which choice
has won: the initial or the modified one. For setting and guessing the
winning shell you can use rnd_integer(1,3).
Then place the game into a loop and iterate through it, e.g., 1000 times,
counting wins for each choice. Finally, use RAISE NOTICE to display the
counter values and determine the winner (or lack thereof).