News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests

Main Menu

Generating random numbers

Started by Diamond Star, December 15, 2013, 10:11:04 AM

Previous topic - Next topic

Diamond Star

Hello
I searched about this subject and find some topics include long and complicated codes
and its not reliable ,So can someone help in putting reliable code do this
and the code should generate new number every time it runs ,not like some codes I saw that generate the same number every time the program runs

jj2007

include \masm32\MasmBasic\MasmBasic.inc        ; download
  Init
  Rand()                ; initialise
  push 100
  .Repeat
        Print Str$(Rand(1000)), " "
        dec stack
  .Until Sign?
  Inkey "ok?"
  Exit
end start

Alex is working on a new version, but even this one is simple, extremely reliable (in terms of ENT performance), and it generates a new series every time you launch the prog. And it's one of the fastest PRNGs available.

qWord

A simple solution is to use Window's Cryptography API.
include \masm32\include\Advapi32.inc
includelib \masm32\lib\Advapi32.lib
...
RandomBytes proc dwLength:DWORD,pBuffer:PVOID
LOCAL hProvider:HANDLE

    invoke CryptAcquireContext,ADDR hProvider,0,0,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT or CRYPT_SILENT
    invoke CryptGenRandom,hProvider,dwLength,pBuffer
    invoke CryptReleaseContext,hProvider, 0
    ret

RandomBytes endp
MREAL macros - when you need floating point arithmetic while assembling!

dedndave


hutch--

Random algos generally need to be "seeded" and if you keep using the same seed number, you will keep getting the same result. The trick is to use a different seed each time you run the algo if you want different sequences each time.

dedndave

the one i use is auto-seeding   :biggrin:
it doesn't re-seed on every call, but it re-seeds once every 128 to 255 calls
(the re-seed iteration count is also random)

hutch--

That's fine as long as you never need a repeatable sequence.

Vortex

Another one :

include     RndNumb.inc

.data

format1     db 'Random number = %d',13,10,0

.code

start:

    call    main
    invoke  ExitProcess,0

main PROC uses ebx

LOCAL _st:SYSTEMTIME

    invoke  GetSystemTime,ADDR _st
    movzx   eax,SYSTEMTIME.wMilliseconds[_st]
    invoke  crt_srand,eax

    mov     ebx,10
@@:
    invoke  crt_rand

    and     eax,0000000FFh ; random numbers between 0 - 255

    invoke  crt_printf,ADDR format1,eax
    dec     ebx
    jnz     @b

    ret

main ENDP

END start

Diamond Star

Thanks for everyone add thing here
I'll try them and see what the best

I appreciate your efforts all

Diamond Star

IThank you all
I find te best one is Aseed4 sample that is added by dedndave
it is good and useful

dedndave

 :P

it does spit out good random garbage
great for games and similar applications
the older versions were a bit slower, but this one is quite fast