Generate random numbers avoiding duplicates
[Autolink] Menu
/* sample code for the random number generator routine */
do forever
call LineOut, 'Random number generator'
call LineOut, ''
call LineOut, 'Enter "" to leave'
call Charout, 'Enter min: '
parse pull min
if min = '' then
leave
call Charout, 'Enter max: '
parse pull max
if max = '' then
leave
call Charout, 'Enter count: '
parse pull count
if count = '' then
leave
call LineOut , 'The result is: ' RandomNumbers( min, max, count )
end /* do forever */
exit 0
/* ------------------------------------------------------------------ */
/* function: Generate n random numbers avoiding duplicates */
/* */
/* usage: resultStr = RandomNumbers( min, max, count ) */
/* */
/* where: min - lower limit for the numbers */
/* max - upper limit for the numbers */
/* count - no of random numbers */
/* */
/* returns: The random numbers in a string separated by blanks */
/* or 'ERROR:' in case of a parameter error */
/* */
/* note: The limitations for the random function of the used */
/* REXX interpreter apply to RandomNumbers also */
/* */
/* source: Found in a public news group */
/* */
RandomNumbers: PROCEDURE
parse arg min, max, count
/* install a local error handler */
errorResult = 'ERROR:'
signal on syntax Name RandomNumberError
select
when ( datatype( min, 'N' ) <> 1 | datatype( max, 'N' ) <> 1 ) | ,
( min >= max ) | ( datatype( count, 'N' ) <> 1 ) | ,
count < 0 then
do
/* invalid parameter */
resStr = errorResult
end /* when */
when ( max - min < count ) then
do
/* invalid parameter (leads to an endless loop) */
resStr = errorResult
end /* when */
otherwise
do
resStr = ' '
do until words( resStr ) = count
i = random( min, max )
resStr = overlay( i,resStr,i*3)
end /* do until ... */
end /* otherwise */
end /* select */
return space( resStr )
/* exit handler for syntax errors */
RandomNumberError:
return errorResult
[Back: Convert a decimal number into a system based n]
[Next: Misc. useful routines]