Problem:
How to calculate a random number in COBOL?
Resolution:
The following example shows one method of generating a "random" number. The number generated is not a "true" random number but should suffice for most purposes.
The program is written as a sub-routine that can be called from another COBOL program. To simply pass the maximum value for the range of random numbers (e.g. 100 for a number between 1 and 100) and a variable to pass the result back in.
If it is the first time the program has been called then the random seed is set based on the time to reduce the chance of a duplicate string on random numbers.
working-storage section.
01 ws-first-time pic 9(1) value 0.
01 ws-rnd-seed-x pic x(8).
01 ws-rnd-seed-9 redefines ws-rnd-seed-x
pic 9(8).
01 ws-rnd-dbl comp-2.
* -------------------------------------------------------------- *
linkage section.
01 ls-max pic x comp-x.
01 ls-result pic x comp-x.
* -------------------------------------------------------------- *
procedure division using ls-max
ls-result.
* -- Generate the random seed value if this is the first time the
* -- routine has been called.
if ws-first-time = 0
move 32768 to ws-rnd-seed-9
perform until ws-rnd-seed-9 < 32768
accept ws-rnd-seed-x from time
move function reverse(ws-rnd-seed-x) to ws-rnd-seed-x
compute ws-rnd-seed-9 = ws-rnd-seed-9 / 3060
end-perform
compute ws-rnd-dbl = function random(ws-rnd-seed-9)
move 1 to ws-first-time
end-if.
* -- Generate a random number between 1 and LS-Max.
compute ls-result = (function random() * ls-max) 1.
exit program.
stop run.
* -------------------------------------------------------------- *