ASSEMBLY LANGUAGE - WEEK VII					December 14, 1986



GENERATING A RANDOM NUMBER



The RAM refresh counter in the Z-80 offers the basis for a very satisfactory random number generator. As R is used for refresh and is continually counting from 0 to 127, if the refresh register is read at unpredictable intervals the number returned will be truly random. An example of this would be a CALL to RANDOM after a keypress from the TRS-80 keyboard. If RANDOM is called repetitively to generate, say 100 numbers, the numbers would start to repeat because a machine language loop contains a finite and regular number of steps. The call to RANDOM must be influenced by an external event, such as a key press.

The BASIC ROM of the TRS-80 contains a RANDOM subroutine that starts at 01D3H. This routine reads the refresh register and stores the number read at memory location 40ABH. This random number seed is used by the Random Number Generator routine to generate a random number between 0 and 1 or between 0 and xx, where xx is any number less than 32565.



One of the main rules in random number generation is this: Never use any old algorithm to generate what you think will be a string of random numbers. There are several tried and true algorithms for random number generation.

The easiest method is use the method that BASIC already has. The ROM subroutine RND(X) (located  14CCH) requires and integer operand, X, which is used to establish the "range" of the pseudo-random integer number generated, from 1 to X. Typically the ROM subroutine CINT (located @ 0A7FH) is placed after RND(X) to convert the output to an integer.



To use RND(X) in your program, you must load the HL register pair with the non-zero integer value of X, in the range of 1 to 32565, and then call RND(X). Assuming a call to CINT follows RND(X), the integer result is returned in the HL register pair and is stored in memory at 4121H and 4122H. This RND(X) routine uses all the registers, so you must save anything that you need later before calling this routine. 

It would also be nice to be able to see what the decimal value of that number is we generated. If we use a binary to decimal conversion, and store our decimal conversion as a string of ASCII characters, we should be able to list our random number to the screen.




An outline of what we want to do could be listed as follows:



1. prompt for keypress

2. reseed random number by calling refresh register

3. generate random number

4. store it in memory

5. convert random number to decimal.

         and store as a string of ASCII characters.

6. display random number




A single random number generation routine is attached.
                                                                                                               