wanton7
What is best way to create random numbers for dice roller?
What is best way to create random number for dice roller? I’m planning to create LiveView app to help me and my friends remotely play pen & paper RPG using Savage Worlds system.
Marked As Solved
jerdew
I highly recommend using :rand instead of :crypto.
You aren’t aiming to make the next number unpredictable (this is what :crypto is built for), you’re aiming to make the dice be fair; 1/n even chance for each face.
You’ll have a hard enough time convincing your players that the computer dice aren’t rigged without also having to admit “I wrote my own random number generator”.
For example, the trunc approach suggested above has an unexpected bug in it (even after an edit) and will slightly favor 1, 3 and 5 over 2, 4 and 6:
faces = 6
0..255
|> Enum.map(fn x -> trunc(x * faces / 255) + 1 end)
|> Enum.frequencies()
%{1 => 43, 2 => 42, 3 => 43, 4 => 42, 5 => 43, 6 => 42, 7 => 1}
I show this out in detail because I too have gone down this path of ‘I’m going to roll my own RNG that’s using strong crypto’ when I should have just trusted non-crypto-strength randomness for games.
tl;dr Use :rand.uniform(sides) not :crypto.
Also Liked
dimitarvp
To get stronger and less predictable randomness the recommended API is :crypto.strong_rand_bytes.
adamu
<<byte>> = :crypto.strong_rand_bytes(1)
trunc(byte * faces / 256) + 1
edit: fixed off-by-one error (x2
)
edit3: Actually this is still not uniform. I give up. ![]()
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









