Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java
x.get((int)(Math.random()*x.size()))

Consider reusing the Random object, don't create it each time you pick an element.
import java.util.concurrent.ThreadLocalRandom;
x.get(ThreadLocalRandom.current().nextInt(0, x.size()))

Using ThreadLocalRandom prevents unnecessary allocation of a new Random, and is more efficient in a multi-threaded application
import java.util.Random;
if (!x.isEmpty()) {
    Random r = new Random();
    T t = x.get(r.nextInt(x.size()));
}
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;

New implementation...