Logo

Programming-Idioms

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

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Fortran implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
import java.util.Random;
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}
#include <stdlib.h>
int pick(int a, int b)
{
	int upper_bound = b - a + 1;
	int max = RAND_MAX - RAND_MAX % upper_bound;
	int r;

	do {
		r = rand();
	} while (r >= max);
	r = r % upper_bound;
	return a + r;
}
rand(a..b)
import "math/rand"
func pick(a,b int) int {
	return a + rand.Intn(b-a+1)
}
function pick(a, b) {
    return a + Math.floor(Math.random() * (b - a + 1));
}
import random
random.randint(a,b)
rand($a, $b)
import util.Random
a + Random.nextInt(b + 1)
my ($min, $max) = (5, 25);
my $val = $min + int(rand($max-$min));
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 std.random;
auto x1 = uniform(a, b+1);
auto x2 = uniform!"[]"(a, b);
import 'dart:math';
int pick(int a, int b) => a + Random().nextInt(b - a + 1);
uses Math;
var
  _a, _b, _r: Integer;
begin
  _r := RandomRange(_a, _b);
end; 
crypto:rand_uniform(A, B)
import System.Random
let pick (a, b) = randomRIO (a, b) :: IO Integer
 in pick (1, 6) >>= print

(+ a (rand-int (- b a)))
:crypto.rand_uniform(a, b)
math.random(a, b)
using System;
Random r = new Random();
return r.Next(a, b + 1);
a - 1 + :rand.uniform(b-a+1)
#include <random>
std::mt19937 gen;
std::uniform_int_distribution<size_t> uid (a, b);
uid (gen);
use rand::distributions::Distribution;
use rand::distributions::Uniform;
Uniform::new_inclusive(a, b).sample(&mut rand::thread_rng())
a+arc4random_uniform(b+1)
(+ a (random (add1 (- b a))))
(floor (+ a (* (add1 (- b a)) (random 1.0))))
using System;
Random.Shared.Next(a, b + 1)
(a to: b) atRandom
fun pick(a: Int, b: Int): Int {
    return (a..b).random()
}
with Ada.Numerics.Discrete_Random;
declare
   subtype Random_Range is Integer range A .. B;
   package Rand is
      new Ada.Numerics.Discrete_Random (Random_Range);
   use Rand;
   Gen    : Generator;
   Result : Random_Range;
begin
   Reset (Gen);
   Result := Random (Gen);
end;
(defun r (a  b)
(+ a (random (+ 1 (- b a )))))