星期二, 10月 31, 2023

2000-12-20 如何在一指定範圍內產生不重複的隨機變數?



2000-12-20 如何在一指定範圍內產生不重複的隨機變數?

QRPGLESRC RANDOMNUMR RPGLE

* Random numbers without duplicates
* Display list of unique random numbers
* Original: V5R1 RPGIV free format by Hans Boldt (boldt@ca.ibm.com)
* Modified: V4R4 RPGIV by Vengoal Chang
* CRTBNDRPG PGM(RANDOMNUMR) DFTACTGRP(*NO) BNDDIR(QC2LE)

H dftactgrp(*no) bnddir('QC2LE')

D NUMBER c 6
D LOVALUE c 1
D VALUES c 30
D rand pr 10i 0 extproc('rand')
D i s 10i 0
D num s 10i 0
D swap s 10i 0
D numbers s 10i 0 dim(VALUES)
D arr s 10i 0 dim(NUMBER)
D str s 50a varying

*/free // Initialize list of possible values
C for i = 1 to VALUES
C Eval numbers(i) = i + LOVALUE - 1
C endfor

*// Keep looping until we have enough unique numbers
C for i = 1 to NUMBER
C*// Compute random number in range i..VALUES
C eval num = %div(rand * (VALUES+1-i): 32768) + i
*// Swap numbers
C eval swap = numbers(i)
C eval numbers(i) = numbers(num)
C eval numbers(num) = swap
C endfor

*// Assign first 6 numbers to result array
C eval arr = numbers

*// What the heck, let's sort the list of numbers
C sorta arr

*// Show list of numbers
C for i = 1 to NUMBER
C eval str = str + %char(arr(i)) + ' '
C endfor

C str dsply

C eval *inlr = *on


沒有留言: