SQL> REM 05-RAND.SQL
SQL> REM This file contains the code for the Random package in
SQL> REM Chapter 5 of "Oracle PL/SQL Programming". It illustrates
SQL> REM package initialization.
SQL>
SQL> REM This is version 1.0 of this file, updated 2/18/96.
SQL> REM Comments and questions should go to Scott Urman at
SQL> REM surman@us.oracle.com.
SQL>
SQL>
SQL> CREATE OR REPLACE PACKAGE Random AS
2 /* Random number generator. Uses the same algorithm as the
3 rand() function in C. */
4
5 -- Used to change the seed. From a given seed, the same
6 -- sequence of random numbers will be generated.
7 PROCEDURE ChangeSeed(p_NewSeed IN NUMBER);
8
9 -- Returns a random integer between 1 and 32767.
10 FUNCTION Rand RETURN NUMBER;
11 --PRAGMA RESTRICT_REFERENCES(rand, WNDS );
12
13 -- Same as Rand, but with a procedural interface.
14 PROCEDURE GetRand(p_RandomNumber OUT NUMBER);
15
16 -- Returns a random integer between 1 and p_MaxVal.
17 FUNCTION RandMax(p_MaxVal IN NUMBER) RETURN NUMBER;
18 -- PRAGMA RESTRICT_REFERENCES(RandMax, WNDS);
19
20 -- Same as RandMax, but with a procedural interface.
21 PROCEDURE GetRandMax(p_RandomNumber OUT NUMBER,
22 p_MaxVal IN NUMBER);
23 END Random;
24 /
Package created.
SQL>
SQL> CREATE OR REPLACE PACKAGE BODY Random AS
2
3 /* Used for calculating the next number. */
4 v_Multiplier CONSTANT NUMBER := 22695477;
5 v_Increment CONSTANT NUMBER := 1;
6
7 /* Seed used to generate random sequence. */
8 v_Seed number := 1;
9
10 PROCEDURE ChangeSeed(p_NewSeed IN NUMBER) IS
11 BEGIN
12 v_Seed := p_NewSeed;
13 END ChangeSeed;
14
15 FUNCTION Rand RETURN NUMBER IS
16 BEGIN
17 v_Seed := MOD(v_Multiplier * v_Seed + v_Increment,
18 (2 ** 32));
19 RETURN BITAND(v_Seed/(2 ** 16), 32767);
20 END Rand;
21
22 PROCEDURE GetRand(p_RandomNumber OUT NUMBER) IS
23 BEGIN
24 -- Simply call Rand and return the value.
25 p_RandomNumber := Rand;
26 END GetRand;
27
28 FUNCTION RandMax(p_MaxVal IN NUMBER) RETURN NUMBER IS
29 BEGIN
30 RETURN MOD(Rand, p_MaxVal) + 1;
31 END RandMax;
32
33 PROCEDURE GetRandMax(p_RandomNumber OUT NUMBER,
34 p_MaxVal IN NUMBER) IS
35 BEGIN
36 -- Simply call RandMax and return the value.
37 p_RandomNumber := RandMax(p_MaxVal);
38 END GetRandMax;
39
40 BEGIN
41 /* Package initialization. Initialize the seed to the current
42 time in seconds. */
43 ChangeSeed(TO_NUMBER(TO_CHAR(SYSDATE, 'SSSSS')));
44 END Random;
45 /
Package body created.
SQL>
|