# Idiom #11 Pick a random element from a list

The list x must be non-empty.

use rand::seq::SliceRandom;
let choice = x.choose(&mut rng).unwrap();
use rand::{self, Rng};
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
Generator : Random_Index.Generator;
begin
Random_Index.Reset (Generator);
return X (Random_Index.Random (Generator));
end Pick_Random;
#include <stdlib.h>
x[rand() % x_length];
(rand-nth x)
#include <random>
std::mt19937 gen;
std::uniform_int_distribution<size_t> uid (0, x.size () - 1);
x[uid (gen)];
#include <random>
#include <algorithm>
std::ranges::sample(x, &result, 1, std::mt19937{std::random_device{}()});
using System;
x[new Random().Next(x.Count)]
using System;
x[Random.Shared.Next(x.Count)]
import std.random;
x.randomSample(1);
x[new Random().nextInt(x.length)];
Enum.random(x)
https://github.com/inaka/erlang-katana
ktn_random:pick(X)
lists:nth(rand:uniform(length(X)), X).

call random_number (a)
x(lbound(x) + int(a*ubound(x))
import "math/rand"
func pickT(x []T) T {
return x[rand.Intn(len(x))]
}
func pick[T any](x []T) T {
return x[rand.Intn(len(x))]
}
import "math/rand"
x[rand.Intn(len(x))]
x.shuffled().first()
import System.Random (randomRIO)
(l !!) <\$> randomRIO (0, length l - 1)
import System.Random (randomR)
(\l g -> l !! fst (randomR (0, length l) g))
x[~~(Math.random() * x.length)];
x[Math.floor(Math.random() * x.length)]
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
if(x != null && x.size() > 0) {
Random random = new Random();
T item = x.get(random.nextInt(x.size()));
}
x.get((int)(Math.random()*x.size()))
list.random()
(nth (random (length x)) x)
x[math.random(#x)]
x[arc4random_uniform(x.count)]
\$x[ array_rand(\$x) ]
uses classes;
element := x.Items[random(x.count)];
element := x[random(length(x))];
my @x = ('a', 'list', 'of', 'random', 'items');
print \$x[rand @x];
import random
random.choice(x)
x.sample
import scala.util.Random
val x = List(1, 2, 3, 4)
x.apply(Random.nextInt(x.size))
(list-ref x (random (length x)))
x atRandom
Imports System
x(Random.Shared.Next(x.Count))
Imports System
x(New Random().Next(x.Count))

programming-idioms.org