The MASM Forum

General => The Workshop => Topic started by: jj2007 on August 26, 2017, 01:17:10 PM

Title: Skewed random numbers
Post by: jj2007 on August 26, 2017, 01:17:10 PM
Imagine you have a table of probabilities in the data section:
Code: [Select]
pTable dd 25, 55, 15, 3, 2, 0 ; zero-delimited table holds the relative probabilities
For illustrative purposes, the sum is 100 in this case, but it could be any combination of frequencies.

Goal is to obtain random numbers that are distributed according to this table's frequencies, for example:
Code: [Select]
2499
5501
1499
 300
 199

The source:

include \Masm32\MasmBasic\Res\JBasic.inc        ; download (http://masm32.com/board/index.php?topic=94.0)

.data
pTable  dd 25, 55, 15, 3, 2, 0  ; zero-delimited table holds the relative probabilities
pCount  dd 6 dup(?)             ; result counter

  Init
  PrintLine Chr$("This code was assembled with ", @AsmUsed$(1), " in ", jbit$, "-bit format")
  Rand(pt:offset pTable)        ; probability table: pointer

        xor ebx, ebx
@@:     void Rand(pt)           ; void because Rand(pt) returns eax (we need rax)
        lea rdi, pCount
        inc dword ptr [rdi+4*rax]       ; eax will be in the range 0...4
        inc ebx
        cmp ebx, 9999999
        jb @B

        xor ebx, ebx
@@:     lea rdi, pCount
        Print Str$("%i\n", dword ptr [rdi+4*rbx])       ; display the results
        inc rbx
        cmp rbx, 5
        jb @B
EndOfCode


Output:
Code: [Select]
This code was assembled with ml64 in 64-bit format
2499469
5501160
1499102
300666
199602

Project attached - it works also with ordinary 32-bit MB ;)