Some debugging techniques
Run the program below.
It is designed to create 3 numbers rather than 5
It is designed for a max of 4
Why? Because the likelyhood of getting a duplicate
is so low for 5 numbers in the range 0-49 that you
can't test that case. This means someday your program
will go down a path that was not tested. BAD. With the
new values, it is surely tested.
Run it like this:
Either compile and run the EXE, or from the DOS prompt
START QBASIC / RUN Z
(where you have Z.BAS in NOTEPAD (ASCII) format.
Keep pressing ENTER until you are satisfied. Voil?,
your program is debugged. You can play around with
other values to see what happens for bigger values.
Change the CONSTs for 20 numbers in the range < 22.
To stop the program, don't just press Enter, but
instead enter something such as "q".
Anyway, to meet your original specification you just
have to change the CONSTs to
CONST maxCNT = 5
CONST maxN = 50
and be confident that if 32 were generated twice by
RND, no problem - your program will handle it.
Mac
Code: Select all
CLS
RANDOMIZE TIMER
CONST maxCNT = 3: ' Don't hard code 5's
CONST maxN = 4: ' Don't hard code 50
DIM N AS INTEGER ' A candidate integer
DIM l(maxCNT) AS INTEGER ' Accepted candidates
DIM cnt AS INTEGER ' Count of accepted candidates
DIM dup AS INTEGER ' 0=No -1=Yes
DIM i AS INTEGER, j AS INTEGER ' Work variables
' ### Generate the numbers
DO
dup = 0
N = INT(RND * maxN)
FOR i = 1 TO cnt
IF N = l(i) THEN dup = -1: EXIT FOR
NEXT i
IF NOT dup THEN cnt = cnt + 1: l(i) = N
LOOP WHILE cnt < maxCNT
' ### Sort them
FOR i = 1 TO maxCNT - 1
FOR j = i TO maxCNT
IF l(i) > l(j) THEN SWAP l(i), l(j)
NEXT j
NEXT i
' ### Compute total while printing entries
DIM Total AS INTEGER
FOR i = 1 TO maxCNT
PRINT l(i);
Total = Total + l(i)
NEXT i
PRINT : PRINT : PRINT : PRINT "Total is"; Total
' Exit the program
LOCATE 25, 5
LINE INPUT "Enter nothing to run again, something like 'q' to exit: "; e$
IF e$ = "" THEN RUN
CLS
SYSTEM