Pick random element

From Rosetta Code
Task
Pick random element
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to pick a random element from a list.

ACL2[edit]

:set-state-ok t
 
(defun pick-random-element (xs state)
(mv-let (idx state)
(random$ (len xs) state)
(mv (nth idx xs) state)))

Ada[edit]

The following program generates three 20-letter words. Each vowel and each consonant is picked randomly from a list of vowels resp. a list of consonants.

with Ada.Text_IO, Ada.Numerics.Float_Random;
 
procedure Pick_Random_Element is
 
package Rnd renames Ada.Numerics.Float_Random;
Gen: Rnd.Generator; -- used globally
 
type Char_Arr is array (Natural range <>) of Character;
 
function Pick_Random(A: Char_Arr) return Character is
-- Chooses one of the characters of A (uniformly distributed)
begin
return A(A'First + Natural(Rnd.Random(Gen) * Float(A'Last)));
end Pick_Random;
 
Vowels  : Char_Arr := ('a', 'e', 'i', 'o', 'u');
Consonants: Char_Arr := ('t', 'n', 's', 'h', 'r', 'd', 'l');
Specials  : Char_Arr := (',', '.', '?', '!');
 
begin
Rnd.Reset(Gen);
for J in 1 .. 3 loop
for I in 1 .. 10 loop
Ada.Text_IO.Put(Pick_Random(Consonants));
Ada.Text_IO.Put(Pick_Random(Vowels));
end loop;
Ada.Text_IO.Put(Pick_Random(Specials) & " ");
end loop;
Ada.Text_IO.New_Line;
end Pick_Random_Element;
Output:
horanohesuhodinahiru. desehonirosedisinelo, losihehederidonolahe?

Aime[edit]

list l;
 
l_append(l, 'a');
l_append(l, 'b');
l_append(l, 'c');
l_append(l, 'd');
l_append(l, 'e');
l_append(l, 'f');
 
o_byte(l_query(l, drand(5)));
o_byte('\n');

ALGOL 68[edit]

Works with: ALGOL 68G version Any - tested with release 2.8.win32
# pick a random element from an array of strings #
 
OP PICKRANDOM = ( []STRING list )STRING:
BEGIN
 
INT number of elements = ( UPB list - LWB list ) + 1;
INT random element =
ENTIER ( next random * ( number of elements ) );
 
list[ LWB list + random element ]
END; # PICKRANDOM #
# can define additional operators for other types of array #
 
 
main: (
 
[]STRING days = ( "Sunday", "Monday", "Tuesday", "Wednesday"
, "Thursday", "Friday", "Saturday"
);
 
print( ( PICKRANDOM days, newline ) )
 
)
Output:
Thursday

App Inventor[edit]

App Inventor has the block pick a random item for selecting a random item from a list.
CLICK HERE TO VIEW THE BLOCKS AND ANDROID APP DISPLAY

AutoHotkey[edit]

True Arrays
Works with: AutoHotkey_L
list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint]
Pseudo-Arrays
Works with: AutoHotkey_Basic
list := "abc,def,gh,ijklmnop,hello,world"
StringSplit list, list, `,
Random, randint, 1, %list0%
MsgBox % List%randint%

AWK[edit]

 
# syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK
BEGIN {
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",")
srand()
x = int(n*rand()) + 1
printf("%s\n",day_of_week[x])
exit(0)
}
 
Output:
GAWK -f PICK_RANDOM_ELEMENT.AWK
Sunday
GAWK -f PICK_RANDOM_ELEMENT.AWK
Monday
GAWK -f PICK_RANDOM_ELEMENT.AWK
Wednesday
GAWK -f PICK_RANDOM_ELEMENT.AWK
Tuesday

Bash[edit]

# borrowed from github.com/search?q=bashnative
 
rand() {
printf $(( $1 * RANDOM / 32767 ))
}
rand_element () {
local -a th=("$@")
unset th[0]
printf $'%s\n' "${th[$(($(rand "${#th[*]}")+1))]}"
}
 
echo "
You feel like a $(rand_element pig donkey unicorn eagle) today"

BASIC[edit]

Works with: QBasic
Works with: PowerBASIC

Note the use of LBOUND and UBOUND. This is only necessary for arrays where the lower and upper limits aren't known. In this example, we know they are 0 and 10 respectively, and could have hard-coded those numbers. (For that matter, the "random selection" line could've just been entered as x = INT(RND * 11).)

'setup
DIM foo(10) AS LONG
DIM n AS LONG, x AS LONG
FOR n = LBOUND(foo) TO UBOUND(foo)
foo(n) = INT(RND*99999)
NEXT
RANDOMIZE TIMER
 
'random selection
x = INT(RND * ((UBOUND(foo) - LBOUND(foo)) + 1))
 
'output
PRINT x, foo(x)

See also: Liberty BASIC, PureBasic, Run BASIC

Batch File[edit]

Since there is no arrays in Batch File, I will use a 1-based pseudo-array.

@echo off
setlocal enabledelayedexpansion

::Initializing the pseudo-array...

set "pseudo=Alpha Beta Gamma Delta Epsilon"
set cnt=0 & for %%P in (!pseudo!) do (
set /a cnt+=1
set "pseudo[!cnt!]=%%P"
)
::Do the random thing...
set /a rndInt=%random% %% cnt +1

::Print the element corresponding to rndint...

echo.!pseudo[%rndInt%]!
pause
exit /b
Sample Outputs:
Delta
Press any key to continue . . .

Gamma
Press any key to continue . . .

Epsilon
Press any key to continue . . .

Gamma
Press any key to continue . . .

BBC BASIC[edit]

      DIM list$(5)
list$() = "The", "five", "boxing", "wizards", "jump", "quickly"
chosen% = RND(6)
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'"
Output:
Item 4 was chosen which is 'wizards'

Burlesque[edit]

 
blsq ) "ABCDEFG"123456 0 6rn-]!!
'G
 

123456 is the random seed. In order to pick another element you have to change the random seed.

C[edit]

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
char array[] = { 'a', 'b', 'c' };
 
srand( time( 0 ) );
 
printf( "%c\n", array[ rand() % 3 ] );
 
return 0;
}

C++[edit]

#include <iostream>
#include <random>
#include <vector>
 
int main( ) {
std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
std::random_device seed ;
// generator
std::mt19937 engine( seed( ) ) ;
// number distribution
std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
std::cout << "random element picked : " << numbers[ choose( engine ) ]
<< " !\n" ;
return 0 ;
}

C#[edit]

using System;
using System.Collections.Generic;
 
class RandomElementPicker {
static void Main() {
var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
var rng = new Random();
var randomElement = list[rng.Next(list.Count)];
Console.WriteLine("I picked element {0}", randomElement);
}
}

Ceylon[edit]

import ceylon.random {
 
DefaultRandom
}
 
shared void run() {
value random = DefaultRandom();
value element = random.nextElement([1, 2, 3, 4, 5, 6]);
print(element);
}

Clojure[edit]

(rand-nth coll)

where coll is some sequential collection. Equivalent to:

(nth coll (rand-int (count coll)))

COBOL[edit]

Works with: GNU Cobol
       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. random-element.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 nums-area VALUE "123456789".
03 nums PIC 9 OCCURS 9 TIMES.
 
01 random-idx PIC 9 COMP.
 
PROCEDURE DIVISION.
COMPUTE random-idx = FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:7)) * 9 + 1
DISPLAY nums (random-idx)
.
END PROGRAM random-element.

CoffeeScript[edit]

array = [1,2,3]
console.log array[Math.floor(Math.random() * array.length)]

Common Lisp[edit]

(defvar *list* '(one two three four five))
 
(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*))
Output:
FIVE 
THREE 
ONE

D[edit]

import std.stdio, std.random;
 
void main() {
const items = ["foo", "bar", "baz"];
items[uniform(0, $)].writeln;
}

Delphi[edit]

See #Pascal / Delphi / Free Pascal.

Déjà Vu[edit]

!print choose [ "one" "two" "chicken" ]

EchoLisp[edit]

 
(define (pick-random list)
(list-ref list (random (length list))))
(pick-random (iota 1000))667
(pick-random (iota 1000))179
 

Elena[edit]

#import system.
#import extensions.
 
#class(extension)listOp
{
#method randomItem
= self @ (randomGenerator eval:(self length)).
}
 
#symbol program =
[
#var item := (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
 
console writeLine:"I picked element ":(item randomItem).
].
 

Elixir[edit]

Works with: Elixir version 1.2
iex(1)> list = Enum.to_list(1..20)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
iex(2)> Enum.random(list)
19
iex(3)> Enum.take_random(list,4)
[19, 20, 7, 15]

Erlang[edit]

% Implemented by Arjun Sunel
-module(pick_random).
-export([main/0]).
 
main() ->
List =[1,2,3,4,5],
Index = random:uniform(length(List)),
lists:nth(Index,List).
 

Euphoria[edit]

constant s = {'a', 'b', 'c'}
puts(1,s[rand($)])

Factor[edit]

( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a"

Falcon[edit]

 
lst = [1, 3, 5, 8, 10]
> randomPick(lst)
 

Fortran[edit]

Works with: Fortran version 90 and later
program pick_random
implicit none
 
integer :: i
integer :: a(10) = (/ (i, i = 1, 10) /)
real :: r
 
call random_seed
call random_number(r)
write(*,*) a(int(r*size(a)) + 1)
end program

Free Pascal[edit]

See #Pascal / Delphi / Free Pascal.

F#[edit]

let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)]

GAP[edit]

a := [2, 9, 4, 7, 5, 3];
Random(a);

This works with many GAP objects, for instance groups:

Random(SymmetricGroup(20));
 
(1,4,8,2)(3,12)(5,14,10,18,17,7,16)(9,13)(11,15,20,19)

Go[edit]

package main
 
import (
"fmt"
"math/rand"
"time"
)
 
var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}
 
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(list[rand.Intn(len(list))])
}

Groovy[edit]

Solution:

def list = [25, 30, 1, 450, 3, 78]
def random = new Random();
 
(0..3).each {
def i = random.nextInt(list.size())
println "list[${i}] == ${list[i]}"
}
Output:
list[3] == 450
list[2] == 1
list[5] == 78
list[3] == 450

Alternate Solution:

 
[25, 30, 1, 450, 3, 78].sort{new Random()}?.take(1)[0]
 

Haskell[edit]

Creating a custom function:

import Random (randomRIO)
 
pick :: [a] -> IO a
pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)
 
x <- pick [1 2 3]

Using the random-extras library:

import Data.Random
import Data.Random.Source.DevRandom
import Data.Random.Extras
 
x <- runRVar (choice [1 2 3]) DevRandom


Using Generator Combinators from Test.QuickCheck

import Test.QuickCheck (generate, elements)
 
x <- (generate . elements) [1, 2, 3]

Icon and Unicon[edit]

The unary operator '?' selects a random element from its argument which may be a string, list, table, or set.

procedure main()
L := [1,2,3] # a list
x := ?L # random element
end

J[edit]

   ({~ ?@#) 'abcdef'
b

Java[edit]

import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used

For a List object rather than an array, substitute list.get(...) for array[...]. If preserving the order of the List isn't important, you could call Collections.shuffle(list); and then list.get(0);. You would need to shuffle each time unless you removed the item from the list.

JavaScript[edit]

var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];

Julia[edit]

array = [1,2,3]
array[rand(1:length(array))]

K[edit]

  1?"abcdefg"
,"e"

LabVIEW[edit]

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
LabVIEW Pick random element.png

Lasso[edit]

local(
my array = array('one', 'two', 3)
)
 
#myarray -> get(integer_random(#myarray -> size, 1))

-> two

Liberty BASIC[edit]

The natural way to hold an array of text is in a space- or comma-delimited string, although an array could be used.

list$ ="John Paul George Ringo Peter Paul Mary Obama Putin"
wantedTerm =int( 10 *rnd( 1))
print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")
Selecting term 5 in the list, which was Peter

LiveCode[edit]

put "Apple,Banana,Peach,Apricot,Pear" into fruits
put item (random(the number of items of fruits)) of fruits

[edit]

Works with: UCB Logo
pick [1 2 3]

Lua[edit]

math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)])

Mathematica[edit]

RandomChoice[{a, b, c}]
->c

MATLAB / Octave[edit]

In case list is a cell array:

        list = {'a','b','c'}; 
list{ceil(rand(1)*length(list))}

If list is a vector:

        list = 1:1000; 
list(ceil(rand(1)*length(list)))

Maxima[edit]

random_element(l):= part(l, 1+random(length(l)));
/* (%i1) random_element(['a, 'b, 'c]);
(%o1) c
*/

МК-61/52[edit]

0 П0 1 П1 2 П2 3 П3 4 П4 5
 
^ СЧ * [x] ПE КИПE С/П

[edit]

;; from list containnig only literals and literal constants
user-message one-of [ 1 3 "rooster" blue ]
;; from list containing variables and reporters
user-message one-of (list (red + 2) turtles (patch 0 0) )

NetRexx[edit]

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
iArray = [ 1, 2, 3, 4, 5 ] -- a traditional array
iList = Arrays.asList(iArray) -- a Java Collection "List" object
iWords = '1 2 3 4 5' -- a list as a string of space delimited words
 
 
v1 = iArray[Random().nextInt(iArray.length)]
v2 = iList.get(Random().nextInt(iList.size()))
v3 = iWords.word(Random().nextInt(iWords.words()) + 1) -- the index for word() starts at one
 
say v1 v2 v3
 


NewLISP[edit]

 
(define (pick-random-element R)
(nth (rand (length R)) R))
 

Example:

(setq X '("alpha" "beta" "gamma" "delta" "epsilon"))
(println (pick-random-element X))
(println (pick-random-element X))
(println (pick-random-element X))
(println (pick-random-element X))


Nim[edit]

import math
randomize()
 
proc random[T](a: openarray[T]): T =
a[random(a.low..a.len)]
 
let ls = @["foo", "bar", "baz"]
echo ls.random()
 
var xs: array[10..14, string]
for i in 10..14:
xs[i] = "foo: " & $i
 
echo xs.random()

Objeck[edit]

values := [1, 2, 3];
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];

OCaml[edit]

With a list:

let list_rand lst =
let len = List.length lst in
List.nth lst (Random.int len)
# list_rand [1;2;3;4;5] ;;
- : int = 3

With an array:

let array_rand ary =
let len = Array.length ary in
ary.(Random.int len)
# array_rand [|1;2;3;4;5|] ;;
- : int = 3


Oforth[edit]

: pickRand(l)   l size rand l at ;

PARI/GP[edit]

pick(v)=v[random(#v)+1]

Pascal / Delphi / Free Pascal[edit]

Program PickRandomElement (output);
 
const
s: array [1..5] of string = ('1234', 'ABCDE', 'Charlie', 'XB56ds', 'lala');
 
begin
randomize;
writeln(s[low(s) + random(length(s))]);
end.

Perl[edit]

my @array = qw(a b c);
print $array[ rand @array ];

Perl 6[edit]

Works with: rakudo version 2015-12-07

In a nutshell, picking an element from a list is implemented with a method conveniently called "pick":

say (1, 2, 3).pick;

There are various ways of doing something similar, though. Perl 6 has actually two methods (with associated functional forms) to return random elements depending on whether you are doing selection with or without replacement.

Selection with replacement: (roll of a die)

(1..6).roll;    # return 1 random value in the range 1 through 6
(1..6).roll(3); # return a list of 3 random values in the range 1 through 6
(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6

Selection without replacement: (pick a card from a deck)

# define the deck
my @deck = <2 3 4 5 6 7 8 9 J Q K A> X~ <♠ ♣ ♥ ♦>;
@deck.pick; # Pick a card
@deck.pick(5); # Draw 5
@deck.pick(*); # Get a shuffled deck

Or you can always use the normal rand built-in to generate a subscript (which automatically truncates any fractional part):

@array[@array * rand]

However, the pick and roll methods (not to be confused with the pick-and-roll method in basketball) are more general insofar as they may be used on any enumerable type:

say Bool.pick;  # returns either True or False

Phix[edit]

constant s = {'a','b','c'}
puts(1,s[rand(length(s))])

PHP[edit]

$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];

PicoLisp[edit]

(get Lst (rand 1 (length Lst)))

PL/I[edit]

   declare t(0:9) character (1) static initial
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
put ( t(10*random()) );
Output:
e

Powershell[edit]

Powershell has Get-Random Cmdlet which one of its overload is to select randomly from a given list

 
1..100 | Get-Random -Count 3
 

Prolog[edit]

Works with: SWI-Prolog version 6
 
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).
M = i.
 

PureBasic[edit]

Procedure.s pickRandomElement(List source.s())
Protected x = ListSize(source())
 
If x > 0
SelectElement(source(), Random(x - 1)) ;element numbering is zero - based
ProcedureReturn source()
EndIf
EndProcedure
 
;initialize list elements
DataSection
elements:
Data.s "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"
EndDataSection
 
#elementCount = 10
NewList item.s()
 
Restore elements
Define i
For i = 1 To #elementCount
AddElement(item())
Read.s item()
Next
 
If OpenConsole()
Print("Source list: ")
ForEach item()
Print(item() + " ")
Next
PrintN(#CRLF$)
 
Print("Random picks from list: ")
For i = 1 To 10
Print(pickRandomElement(item()) + " ")
Next
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
Output:
Source list:  One Two Three Four Five Six Seven Eight Nine Ten

Random picks from list:  Seven Nine Two Six Four Four Nine Three Six Two

Easy version[edit]

Define.i
OpenConsole()
 
a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+
"Six" +#TAB$+ "Seven"+#TAB$+ "Eight" +#TAB$+ "Nine" +#TAB$+ "Ten" +#TAB$
 
Print("Source list: "+#TAB$+a$+#CRLF$+"Random list: "+#TAB$)
 
For i=1 To CountString(a$,#TAB$)
Print(StringField(a$,Random(CountString(a$,#TAB$),1),#TAB$)+#TAB$)
Next
Input()
Output:
Source list:    One     Two     Three   Four    Five    Six     Seven   Eight   Nine    Ten
Random list:    One     Two     Seven   Nine    Ten     Seven   Three   Five    Ten     Nine

Python[edit]

>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'

R[edit]

# a vector (letters are builtin)
letters
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
# [20] "t" "u" "v" "w" "x" "y" "z"
 
# picking one element
sample(letters, 1)
# [1] "n"
 
# picking some elements with repetition, and concatenating to get a word
paste(sample(letters, 10, rep=T), collapse="")
# [1] "episxgcgmt"

Racket[edit]

 
#lang racket
(define (pick-item l)
(list-ref l (random (length l))))
 

REXX[edit]

version 1[edit]

This REXX example takes the task very literally.

/*REXX program to pick a random element from a list (tongue in cheek). */
 
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen'
_=_ 'fluorine neon sodium magnesium aluminum silicon phosphorous sulfur'
_=_ 'chlorine argon potassium calcium scandium titanium vanadium chromium'
_=_ 'manganese iron cobalt nickel copper zinc gallium germanium arsenic'
_=_ 'selenium bromine krypton rubidium strontium yttrium zirconium'
_=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver'
_=_ 'cadmium indium tin antimony tellurium iodine xenon cesium barium'
_=_ 'lanthanum cerium praseodymium neodymium promethium samarium europium'
_=_ 'gadolinium terbium dysprosium holmium erbium thulium ytterbium'
_=_ 'lutetium hafnium tantalum tungsten rhenium osmium irdium platinum'
_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium'
_=_ 'radium actinium thorium protactinium uranium neptunium plutonium'
_=_ 'americium curium berkelium californium einsteinum fermium mendelevium'
_=_ 'nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium'
_=_ 'meitnerium darmstadtium roentgenium copernicium Ununtrium'
 
w=words(_)
say 'random element =' word(_,random(1,w))
/*stick a fork in it, we're done.*/
Output:
random element = ytterbium

version 2[edit]

Slightly simplified:

Note that this version doesn't work (receives a syntax error 12) with REXXes that have a
smaller limit of the total length of a clause, in particular PC/REXX and Personal REXX
which have a limit of 1,000 characters).

 
/* REXX ***************************************************************
* 18.10.2012 Walter Pachl Not only the list of elements shortened:-)
**********************************************************************/

wl='hydrogen helium lithium beryllium boron carbon nitrogen oxygen',
'fluorine neon sodium magnesium aluminum silicon phosphorous sulfur',
'...',
'meitnerium darmstadtium roentgenium copernicium Ununtrium'
 
Say word(wl,random(1,words(wl)))
 

Ring[edit]

 
aList = "abcdefghij"
for i = 1 to 10
letter = random(10)
if letter > 0
see aList[letter] + nl
ok
next
 

Ruby[edit]

Works with: Ruby version 1.9
irb(main):001:0> %w(north east south west).sample
=> "west"
irb(main):002:0> (1..100).to_a.sample(2)
=> [17, 79]

Run BASIC[edit]

list$  = "a,b,c,d,e,f,g,h,i,j"
letter = rnd(1) * 10
print "Selected letter:"; word$(list$,letter,",")

Scala[edit]

Library: Scala
val a = (1 to 10).toList
 
println(scala.util.Random.shuffle(a).head)

Seed7[edit]

$ include "seed7_05.s7i";
 
const proc: main is func
begin
writeln(rand([] ("foo", "bar", "baz")));
end func;

Sidef[edit]

var arr = %w(north east south west);
say arr.rand;
say arr.rand(2).dump;
Output:
south
['west', 'south']

Smalltalk[edit]

x := #(1 2 3) atRandom.

Swift[edit]

import Darwin
 
let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])

Tcl[edit]

Random selection from a list is implemented by composing lindex (for selection of an item from a list) and the pattern for generating an integral random number from the range . It's simpler to use when wrapped up as a helper procedure:

proc randelem {list} {
lindex $list [expr {int(rand()*[llength $list])}]
}
set x [randelem {1 2 3 4 5}]

TXR[edit]

Translation of: Tcl
@(do (defun randelem (seq)
[seq (random nil (length seq))]))
@(bind x @(randelem #("a" "b" "c" "d")))

TUSCRIPT[edit]

$$ MODE TUSCRIPT
list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin"
sizeList=SIZE(list)
selectedNr=RANDOM_NUMBERS (1,sizeList,1)
selectedItem=SELECT(list,#selectednr)
PRINT "Selecting term ",selectedNr," in the list, which was ",selectedItem
Output:
Selecting term 3  in the list, which was George

Ursa[edit]

# generate a stream (ursa equivalent of a list)
decl string<> str
append "these" "are" "some" "values" str
 
decl ursa.util.random r
out str<(r.getint (size str))> endl console

VBScript[edit]

 
Function pick_random(arr)
Set objRandom = CreateObject("System.Random")
pick_random = arr(objRandom.Next_2(0,UBound(arr)+1))
End Function
 
WScript.Echo pick_random(Array("a","b","c","d","e","f"))
 
Output:
d

XPL0[edit]

code Ran=1, Text=12;
int List;
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX)
Text(0, List(Ran(5)));
]

zkl[edit]

Translation of: XPL0
list:=T("hydrogen", "helium", "lithium", "beryllium", "boron");
list[(0).random(list.len())]