'============================================================================= ' Source code snippet: PowerBASIC for DOS ' ' Author: Brian Mclaughlin (bmclaugh@nwcs.org) ' Copyright status: Public Domain ' ' Generate fast random integers between two values. ' '============================================================================= $LIB ALL OFF DECLARE SUB SeedRand () DECLARE FUNCTION Rand% (BYVAL Low%, BYVAL High%) SeedRand 'seed the thang FOR X% = 1 TO 20 PRINT Rand%(-100, 100) 'the range _includes_ both -100 and 100 NEXT X% END '============= SUB SeedRand '============= SHARED RandSeed% ! Xor AX, AX ; zero out AX ! Mov ES, AX ; point ES at segment 0 (low memory) ! Mov AX, ES:[&H46C] ; AX = low word of timer tick count ! Mov RandSeed%, AX ; save it as the seed END SUB '========================================== FUNCTION Rand% (BYVAL Low%, BYVAL High%) '========================================== LOCAL Result% SHARED RandSeed% ! Mov AX, RandSeed% ; get the latest seed ! Mov BX, 1021 ! Mul BX ; multiply it ! Inc AX ; add one ! Mov BX, &H8000 ; BX = 32768 ! Div BX ; divide it ! Mov RandSeed%, DX ; use the remainder as the next seed ! Mov AX, DX ! Xor DX, DX ; DX:AX now holds the remainder ! Mov CX, High% ; get our upper limit ! Mov BX, Low% ; and our lower limit ! Cmp BX, CX ; see if they are in the right order ! Jle NoSwap ; if they are OK, don't swap them ! Xchg BX, CX ; if they are not OK, swap them NoSwap: ! Sub CX, BX ! Inc CX ; CX = the range from Low% to High% ! Div CX ; divide DX:AX by the range ! Add DX, BX ; add Low% to the remainder ! Mov Result%, DX ; prepare to return our random number Rand% = Result% END FUNCTION