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.
- Ada
- C
- Clojure
- C++
- C++
- C#
- C#
- D
- Dart
- Elixir
- Erlang
- Erlang
- Fortran
- Go
- Go
- Go
- Groovy
- Haskell
- Haskell
- JS
- JS
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
- VB
subtype Element_Type is Integer;
type List_Type is array (Positive range <>) of Element_Type;
function Pick_Random (X : List_Type) return Element_Type is
subtype Index_Range is Positive range X'Range;
package Random_Index is new
Ada.Numerics.Discrete_Random (Index_Range);
Generator : Random_Index.Generator;
begin
Random_Index.Reset (Generator);
return X (Random_Index.Random (Generator));
end Pick_Random;
(rand-nth x)
x[new Random().nextInt(x.length)];
Enum.random(x)
call random_number (a)
x(lbound(x) + int(a*ubound(x))
x[Math.floor(Math.random() * x.length)]
Note that Math.random is not cryptographically secure.
x[~~(Math.random() * x.length)];
~~ is a faster way to call Math.floor().
Note that Math.random is not cryptographically secure.
Note that Math.random is not cryptographically secure.
x.get((int)(Math.random()*x.size()))
Consider reusing the Random object, don't create it each time you pick an element.
if (!x.isEmpty()) {
Random r = new Random();
T t = x.get(r.nextInt(x.size()));
}
list.random()
(nth (random (length x)) x)
x[math.random(#x)]
x[arc4random_uniform(x.count)]
All plain C randoms are available, too; for most ObjC environments this one is preferable
$x[ array_rand($x) ]
array_rand returns the key, and we want the value.
element := x[random(length(x))];
if x is an Array
my @x = ('a', 'list', 'of', 'random', 'items');
print $x[rand @x];
In scalar context (such as the call to rand), an array evaluates to the length.
(list-ref x (random (length x)))
Tested with Chez Scheme
x atRandom