Logo

Programming-Idioms

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

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.

import std.random;
auto x1 = uniform(a, b+1);
auto x2 = uniform!"[]"(a, b);

default boundaries for uniform are exclusive of upper bound, but can be configured as shown for 'x2' example.
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;

Range includes both A and B

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