Program ROLLDIE

We’ll first create a program called ROLLDIE. It simulates

 

the rolling of a single die, returning a random integer

 

between 1 and whatever number is passed into the

 

function.

 

In the Program Catalog create a new program named

 

ROLLDIE. (For help, see page 501.) Then enter the code

 

in the Program Editor.

 

EXPORT ROLLDIE(N)

 

BEGIN

 

RETURN 1+RANDINT(N-1);

 

END;

 

The first line is the heading of the function. Execution of the

 

RETURN statement causes a random integer from 1 to N

 

to be calculated and returned as the result of the function.

 

Note that the RETURN command causes the execution of

 

the function to terminate. Thus any statements between the

 

RETURN statement and END are ignored.

 

In Home view (in fact, anywhere in the calculator where a

 

number can be used), you can enter ROLLDIE(6) and a

 

random integer between 1 and 6 inclusive will be

 

returned.

Program

Because of the EXPORT command in ROLLDIE, another

ROLLMANY

program could use the ROLLDIE function and generate n rolls

 

of a die with any number of sides. In the following program,

 

the ROLLDIE function is used to generate n rolls of two dice,

 

each with the number of sides given by the local variable

 

sides. The results are stored in list L2, so that L2(1) shows

 

the number of times the dies came up with a combined total

 

of 1, L2(2) shows the number of times the dies came up with

 

a combined total of 2, etc. L2(1) should be 0 (since the sum

 

of the numbers on 2 dice must be at least 2).

 

EXPORT ROLLMANY(n,sides)

 

BEGIN

 

LOCAL k,roll;

 

// initialize list of frequencies

 

MAKELIST(0,X,1,2*sides,1) L2;

 

FOR k FROM 1 TO n DO

 

ROLLDIE(sides)+ROLLDIE(sides) roll;

514

Programming in HP PPL

Page 520
Image 520
HP Prime Graphing NW280AAABA manual Program Rolldie, Export Rolldien, Return 1+RANDINTN-1