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

Idiom #15 Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

#include <random>
std::mt19937 gen;
std::uniform_int_distribution<size_t> uid (a, b);
uid (gen);
#include <stdlib.h>
int pick(int a, int b)
{
	return a + rand() % (b - a);
}
-1
( + a (rand-int (- b a)))
using System;
Random r = new Random();
return r.next(a, b + 1);
import std.random;
auto x1 = uniform(a, b+1);
auto x2 = uniform!"[]"(a, b);
import 'dart:math';
int pick(int a, int b) => a + new Random().nextInt(b - a + 1);
a - 1 + :rand.uniform(b-a+1)
:crypto.rand_uniform(a, b)
crypto:rand_uniform(A, B)
import "math/rand"
func pick(a,b int) int {
	return a + rand.Intn(b-a+1)
}
import System.Random
let pick (a, b) = randomRIO (a, b) :: IO Integer
 in pick (1, 6) >>= print

function pick(a, b) {
    return a + Math.floor(Math.random() * (b - a + 1));
}
import java.util.Random;
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}
math.random(a, b)
rand($a, $b)
Math
var
  _a, _b, _r: Integer;
begin
  _r := RandomRange(_a, _b);
end; 
my ($min, $max) = (5, 25);
my $val = $min + int(rand($max-$min));
import random
random.randint(a,b)
rand(a..b)
extern crate rand;
use rand::distributions::{IndependentSample, Range};
fn pick(a: i32, b: i32) -> i32 {
    let between = Range::new(a, b);
    let mut rng = rand::thread_rng();
    between.ind_sample(&mut rng)
}
import util.Random
a + Random.nextInt(b + 1)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms