TIP: Click on subject to list as thread! ANSI
echo: quik_bas
to: ALL
from: DAVID WILLIAMS
date: 1998-04-18 13:32:00
subject: using RND

I've noticed a lot of code posted here recently that doesn't look too
great to me.  In particular, a lot of people seem to use loops that
generate RNDs over and over again until some criterion is satisfied.
This is (almost) *never* necessary!
As an example, look at this little program that I wrote long ago, in a
rather old but still intelligible BASIC. It simulates 6/49 lottery
games, a type that is very popular here in Canada. In these games, six
random integers are chosen in the range 1 to 49. All the selected
integers must be different, and they must be expressed in ascending
numerical order. If you want, try writing a program to do this, before
looking at the code below.
100 ' 6/49 simulator
110 RANDOMIZE TIMER
120 ' create and fill array
130 DIM A%(49)
140 FOR X% = 1 TO 49
150    A%(X%) = X%
160 NEXT
170 K$ = ""
180 ' start of shuffling loop
190 WHILE K$  "n"
200 ' shuffle random 6 numbers into first 6 positions
210   FOR X% = 1 TO 6
220      Y% = X% + INT((50 - X%) * RND)
230      IF Y% > X% THEN SWAP A%(X%), A%(Y%)
240    NEXT
250 ' sort first 6 elements into order
260   FOR X% = 5 TO 1 STEP -1
270      FOR Y% = 1 TO X%
280         IF A%(Y%) > A%(Y% + 1) THEN SWAP A%(Y%), A%(Y% + 1)
290      NEXT
300   NEXT
310 ' print out selection
320   PRINT "Selection is: ";
330   FOR X% = 1 TO 6
340      PRINT A%(X%);
350      IF X% = 6 THEN PRINT ELSE PRINT ",";
360   NEXT
370 ' ask for another selection
380   PRINT "Another selection? ";
390   K$ = ""
400   WHILE K$  "y" AND K$  "n"
410      K$ = INKEY$
420   WEND
430   PRINT K$
440 WEND
450 END
Note that this *never* checks that each new number is different from the
ones that have gone before, since this is *bound* to be true! So there
is no hunting and pecking at RNDs.
Someone may be interested.... !
                              dow
--- PCBoard (R) v15.3 (OS/2) 5
---------------
* Origin: FidoNet: CAP/CANADA Support BBS : 416 287-0234 (1:250/710)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.