Logo

Programming-Idioms

  • Ada
  • JS
  • C++
#include <random>
std::mt19937 gen;
std::uniform_int_distribution<size_t> uid (0, x.size () - 1);
x[uid (gen)];

Assuming that x.size () > 0
#include <random>
#include <algorithm>
std::ranges::sample(x, &result, 1, std::mt19937{std::random_device{}()});
with Ada.Numerics.Discrete_Random;
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;
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.
#include <stdlib.h>
x[rand() % x_length];

rand needs to be initialized by calling void srand(unsigned int);

New implementation...