Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #318 Cryptographically secure random number

Assign to the integer x a random number between 0 and 17 (inclusive), from a crypto secure random number generator.

import secrets
x = secrets.randbelow(18)
import secrets
x = secrets.choice(range(0, 18))
import "crypto/rand"
import "math/big"
bi, err := rand.Int(rand.Reader, big.NewInt(18))
x := int(bi.Int64())
$x = random_int(0, 17)
use Math::Random::Secure qw(irand);
my $x = irand(17);
use Math::Random::Secure qw(rand);
my $x = int(rand(17));
require 'securerandom'
x = SecureRandom.rand(0..17)
use rand::prelude::*;
let mut rng = rand::thread_rng();
let x = rng.gen_range(0..18);

New implementation...
< >
programming-idioms.org