Faster Pseudorandom Numbers

Author(s): Dan Tandberg
Publication: Syntax
Pub Details: Syntax/Syntax ZX80 v4 n10 (Volume 4, Issue 10)
Date: October 1983
Pages: 10

I find the RND function rather slow, especially troublesome when used in realtime graphics games. You can sequentially PEEK from the 8K ROM’s machine language operating system (essentially a pseudorandom number table) from a randomly selected starting point to provide “random” numbers. This method works demonstrably faster than using RND. RUN the following short program in SLOW to randomly place an inverse space in each of the first 22 screen rows.

   1 FOR I=0 TO 21
2 PRINT TAB 32*RND;"█"
3 NEXT I

Execution time: 4.6 seconds. Now try this, also in SLOW:

   1 LET P=RND*1000
2 FOR I=0 TO 21
3 PRINT TAB PEEK (P+I)/8;"█"
4 NEXT I

These lines produce the same display in 3.5 seconds. Line 1 sets P equal to a number between 0 and 999. Line 3 PEEKs the address formed by adding the loop counter I to P. Address P+I always holds a number between 0 and 255, so division by 8 gives pseudorandom numbers between 0 and 31. Generate numbers in any range by picking the proper division and/or algebraically manipulating PEEK (P+I). This technique usually runs about 25% faster than using RND repeatedly.

RACER, following, runs in 2K if you add the following lines to initially fill the display file. (It won’t fit in 1K.) Larger memories do not need these lines.

  22 FOR S=0 TO 21
24 PRINT TAB 31;" "
26 NEXT S

Note lines 40, 90 and 100 work to produce the “winding” of the road. Use this technique to speed up any program using RND. Steer the star down the road using keys Y and 8.

  10 REM "RACER"
20 REM USE "Y" AND "8" TO STEER
30 LET S=0
40 LET R=RND*1000
50 LET G=15
60 LET A=16
70 SCROLL
80 LET XA=A
90 LET N=PEEK (R+S)/256
100 LET G=G+(N>.5 AND G<22)-(N<.5 AND G>0)
110 LET K$=INKEY$
120 LET A=A+(K$="8")-(K$="Y")
130 PRINT AT 21,31;AT 21,G;"███ ███ ";AT 11,A;
140 IF PEEK (PEEK 16398+256*PEEK 16399)<>0 THEN GOTO 180
150 PRINT AT 10,XA;" ";AT 11,A;"*"
160 LET S=S+1
170 GOTO 70
180 PRINT S
190 PAUSE 1E4
200 CLS
210 RUN
SYNTACTIC SUM: 27854, 8K ROM

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.