514 Programming
Program
ROLLMANY
Another 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;
L2(roll)+1L2(roll);
END;
END;
By omitting the EXPORT command when a function is
declared, its visibility can be restricted to the program
within which it is defined. For example, you could define the
ROLLDIE function inside the ROLLMANY program like this:
ROLLDIE();
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;
L2(roll)+1L2(roll);
END;
END;
ROLLDIE(n)
BEGIN
RETURN 1+FLOOR(RANDOM(N));
END;