Logo

Programming-Idioms

  • Lisp
  • Python
  • Java

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 java.util.Random;
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}

For performance, consider reusing the Random object.

(b-a+1) is needed to have upper bound b included.
import java.util.Random;
int v = new Random().nextInt(a, b + 1);
(defun r (a  b)
(+ a (random (+ 1 (- b a )))))
import random
random.randint(a,b)

Upper bound b is included.
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