This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
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.
- Ada
- C
- Clojure
- C++
- C#
- C#
- D
- Dart
- Elixir
- Elixir
- Erlang
- Fortran
- Go
- Go
- Haskell
- JS
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Scheme
- Smalltalk
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;
}
Random.Shared.Next(a, b + 1)
.NET 6 preview 7 adds a thread-safe global Random instance that reduces the need for custom caching of Random instances.
function pick(a, b) {
return a + Math.floor(Math.random() * (b - a + 1));
}
You have to build it from a floating-point random number. It is important to use floor , not round .
programming-idioms.org