### Author Topic: Unique random numbers  (Read 785 times)

#### jj2007

• Moderator
• Member
• Posts: 8776
• Assembler is fun ;-)
##### Unique random numbers
« on: October 27, 2017, 10:00:36 PM »
Probably another useless function, but from time to time the question pops up as an exercise in "high level" language forums, so I thought it might be nice to have it

include \Masm32\MasmBasic\Res\RandUnique.mac    ; included in MasmBasic.inc since 29 Oct 2017
Init
tests=20
Dim MyRand() As DWORD
PrintLine Str\$("Possible range: %i ... ", -tests/2), Str\$(tests/2)
Let edi="unique numbers: "
Rand()                                        ; set a seed value
For_ ecx=0 To tests-1
Rand(-tests/2, tests/2+1, MyRand(ecx), unique)  ; min, max, destination, flag
Let esi=Str\$(" %i ", MyRand(ecx))
.if Instr_(edi, esi)
inc  ebx                ; oops, we got that one already
.else
Let edi=edi+esi         ; remember the last number
.endif
Next
if tests le 100
PrintLine edi                   ; show the unique numbers
endif
Inkey Str\$("-- %i errors, hit any key --", ebx)
EndOfCode

Output:
Code: [Select]
`Possible range: -10 ... 10unique numbers:  -4  5  -9  -5  10  -2  -7  -3  2  -8  -6  8  4  6  9  3  -1  1  7  -10-- 0 errors, hit any key --`
« Last Edit: October 30, 2017, 01:51:00 AM by jj2007 »