Pick random element: Difference between revisions

m
 
(24 intermediate revisions by 18 users not shown)
Line 6:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">print(random:choice([‘foo’, ‘bar’, ‘baz’]))</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
Line 12:
 
For brevity's sake, the implementations of the RNG and printing routines were left out; they can be provided if requested.
<langsyntaxhighlight lang="asm"> .model small
.stack 1024
 
Line 41:
mov ax,4C00h
int 21h ;exit program and return to MS-DOS
end start</langsyntaxhighlight>
 
Line 54:
=={{header|ACL2}}==
 
<langsyntaxhighlight Lisplang="lisp">:set-state-ok t
 
(defun pick-random-element (xs state)
(mv-let (idx state)
(random$ (len xs) state)
(mv (nth idx xs) state)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
DEFINE PTR="CARD"
PTR ARRAY a(7)
Line 80:
PrintE(a(index))
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pick_random_element.png Screenshot from Atari 8-bit computer]
Line 112:
resp. a list of consonants.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Numerics.Float_Random;
 
procedure Pick_Random_Element is
Line 141:
end loop;
Ada.Text_IO.New_Line;
end Pick_Random_Element;</langsyntaxhighlight>
 
{{out}}
Line 147:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">list l;
 
l_append(l, 'a');
Line 157:
 
o_byte(l[drand(5)]);
o_byte('\n');</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># pick a random element from an array of strings #
 
OP PICKRANDOM = ( []STRING list )STRING:
Line 183:
print( ( PICKRANDOM days, newline ) )
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 191:
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang ="apl">pickRandom ← (?≢)⊃⊢</langsyntaxhighlight>
{{out}}
<pre> pickRandom 'ABCDE'
Line 205:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday]</langsyntaxhighlight>
{{out}}
<pre>"two"</pre>
Line 211:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">fruit: ["apple" "banana" "pineapple" "apricot" "watermelon"]
 
print sample fruit</langsyntaxhighlight>
 
{{out}}
Line 222:
; True Arrays
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AHKlang="ahk">list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint]</langsyntaxhighlight>
; Pseudo-Arrays
{{works with|AutoHotkey_Basic}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">list := "abc,def,gh,ijklmnop,hello,world"
StringSplit list, list, `,
Random, randint, 1, %list0%
MsgBox % List%randint%</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK
BEGIN {
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",")
Line 240:
printf("%s\n",day_of_week[x])
exit(0)
}</langsyntaxhighlight>
{{out}}
<pre>GAWK -f PICK_RANDOM_ELEMENT.AWK
Line 254:
This is simply an application of a ranged random number used as an array index. '''BaCon''' has no built in random element selector.
 
<langsyntaxhighlight lang="freebasic">' Pick random element
OPTION BASE 1
DECLARE words$[6]
Line 261:
 
element = RANDOM(6) + 1
PRINT "Chose ", element, ": ", words$[element]</langsyntaxhighlight>
 
{{out}}
Line 272:
 
=={{header|Bash}}==
<langsyntaxhighlight Bashlang="bash"># borrowed from github.com/search?q=bashnative
 
rand() {
Line 283:
}
 
echo "You feel like a $(rand_element pig donkey unicorn eagle) today"</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 291:
Note the use of <code>LBOUND</code> and <code>UBOUND</code>. 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 <code>x = INT(RND * 11)</code>.)
 
<langsyntaxhighlight lang="qbasic">'setup
DIM foo(10) AS LONG
DIM n AS LONG, x AS LONG
Line 303:
 
'output
PRINT x, foo(x)</langsyntaxhighlight>
 
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#Run BASIC|Run BASIC]]
==={{header|Applesoft BASIC}}===
This is the same as the [[#Commodore_BASIC|Commodore BASIC]] solution, except the Commodore timer variable TI is just a regular variable in Applesoft and gets set to a 16-bit random seed value. This is a number which is continually counted up while waiting for a keypress.
<syntaxhighlight lang="qbasic"> 10 DIM A$(9)
20 FOR I = 0 TO 9: READ A$(I): NEXT
25 TI = PEEK(78) + PEEK(79)*256
30 X = RND ( - TI): REM 'PLANT A RANDOM SEED'
40 X = INT ( RND (1) * 10)
50 PRINT A$(X)
60 END
100 DATAALPHA, BRAVO, CHARLIE, DELTA, ECHO
110 DATAFOXTROT, GOLF, HOTEL, INDIA, JULIETT
</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">dim a$ = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
 
for i = 1 to 5
randInt = int(rand * 10)
print a$[randInt]
next i</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
The [[#Commodore BASIC|Commodore BASIC]] solution works without any changes.
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="qbasic">10 DIM A$(9)
20 FOR I=0 TO 9 : READ A$(I) : NEXT
30 X = RND(-TI) : REM 'PLANT A RANDOM SEED'
Line 315 ⟶ 339:
60 END
100 DATA ALPHA, BRAVO, CHARLIE, DELTA, ECHO
110 DATA FOXTROT, GOLF, HOTEL, INDIA, JULIETT</langsyntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">!setup
DIM foo(10)
FOR n = LBOUND(foo) TO UBOUND(foo)
LET foo(n) = INT(RND*99999)
NEXT n
RANDOMIZE
 
!random selection
LET x = INT(RND*((UBOUND(foo)-LBOUND(foo))+1))
 
!output
PRINT x, foo(x)
END</syntaxhighlight>
 
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">dim a$(9)
a$(0)="Zero"
a$(1)="One"
a$(2)="Two"
a$(3)="Three"
a$(4)="Four"
a$(5)="Five"
a$(6)="Six"
a$(7)="Seven"
a$(8)="Eight"
a$(9)="Nine"
 
for i = 1 to 5
randInt = int(ran(10))
print a$(randInt)
next i</syntaxhighlight>
 
=={{header|Batch File}}==
Since there is no arrays in Batch File, I will use a 1-based pseudo-array.
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 334 ⟶ 393:
echo.!pseudo[%rndInt%]!
pause
exit /b</langsyntaxhighlight>
{{Out|Sample Outputs}}
<pre>Delta
Line 349 ⟶ 408:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM list$(5)
list$() = "The", "five", "boxing", "wizards", "jump", "quickly"
chosen% = RND(6)
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'"</langsyntaxhighlight>
{{out}}
<pre>
Line 363 ⟶ 422:
 
Both use BQN's system value <code>•rand</code>, which contains multiple functions for generating random values.
<langsyntaxhighlight lang="bqn">PR ← {𝕩⊑˜•rand.Range ≠𝕩}
PR1 ← •rand.Range∘≠⊸⊑</syntaxhighlight>
(function block)
{{Out|Usage}}
PR1 ← •rand.Range∘≠⊸⊑
<syntaxhighlight lang="bqn"> PR 5‿67‿7‿23
(rand).Range∘≠⊸⊑
PR 5‿67‿7‿23
67
PR1 5‿67‿7‿23
7</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) "ABCDEFG"123456 0 6rn-]!!
'G
</syntaxhighlight>
</lang>
 
''123456'' is the random seed. In order to pick another element you have to change the random seed.
Line 383 ⟶ 441:
=={{header|C}}==
 
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 400 ⟶ 458:
return 0;
}
</syntaxhighlight>
</lang>
Output
<pre>
Line 437 ⟶ 495:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 447 ⟶ 505:
Console.WriteLine("I picked element {0}", randomElement);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
#include <vector>
Line 464 ⟶ 522:
<< " !\n" ;
return 0 ;
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">import ceylon.random {
 
DefaultRandom
Line 476 ⟶ 534:
value element = random.nextElement([1, 2, 3, 4, 5, 6]);
print(element);
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang Clojure="clojure">(rand-nth coll)</langsyntaxhighlight>
 
where <code>coll</code> is some sequential collection. Equivalent to:
 
<langsyntaxhighlight Clojurelang="clojure">(nth coll (rand-int (count coll)))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">random_element = proc [T: type] (a: array[T]) returns (T)
return(a[array[T]$low(a) + random$next(array[T]$size(a))])
end random_element
Line 500 ⟶ 558:
stream$putl(po, random_element[string](arr))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>qux
Line 510 ⟶ 568:
=={{header|COBOL}}==
{{works with|GNU Cobol}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. random-element.
Line 525 ⟶ 583:
DISPLAY nums (random-idx)
.
END PROGRAM random-element.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">array = [1,2,3]
console.log array[Math.floor(Math.random() * array.length)]</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(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*))</langsyntaxhighlight>
 
{{out}}
Line 544 ⟶ 602:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
puts [1, 2, 3, 4, 5].sample(1)
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random;
 
void main() {
const items = ["foo", "bar", "baz"];
items[uniform(0, $)].writeln;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
{{trans|C}}
<syntaxhighlight lang="dart">import 'dart:math';
 
void main() {
final array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
int i;
 
for (i = 1; i < 30; i++) {
var intValue = Random().nextInt(i) % 10;
print(array[intValue]);
}
}</syntaxhighlight>
 
=={{header|Delphi}}==
Line 560 ⟶ 632:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">!print choose [ "one" "two" "chicken" ]</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight>
<lang easyprog.online>ar$[] = [ "spring" "summer" "autumn" "winter" ]
ar$[] = [ "spring" "summer" "autumn" "winter" ]
print ar$[random len ar$[]]</lang>
print ar$[randint len ar$[]]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define (pick-random list)
(list-ref list (random (length list))))
(pick-random (iota 1000)) → 667
(pick-random (iota 1000)) → 179
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
extension listOp
{
randomItem()
= self[randomGenerator.evalnextInt(self.Length)];
}
Line 590 ⟶ 664:
console.printLine("I picked element ",item.randomItem())
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">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]</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(defun random-choice (items)
(nth (random (length items)) items))
 
(random-choice '("a" "b" "c"))
;; => "a"</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
for each int i in range(5)
writeLine(random(text["Dee", "do", "de", "de"]))
end
</syntaxhighlight>
{{out}}
<pre>
do
de
do
de
Dee
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(pick_random).
-export([main/0]).
Line 617 ⟶ 706:
Index = rand:uniform(length(List)),
lists:nth(Index,List).
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant s = {'a', 'b', 'c'}
puts(1,s[rand($)])</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)]</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a"</langsyntaxhighlight>
 
=={{header|Falcon}}==
<langsyntaxhighlight lang="falcon">
lst = [1, 3, 5, 8, 10]
> randomPick(lst)
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program pick_random
implicit none
 
Line 650 ⟶ 739:
call random_number(r)
write(*,*) a(int(r*size(a)) + 1)
end program</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
Line 656 ⟶ 745:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Line 667 ⟶ 756:
Print a(randInt)
Next
Sleep</langsyntaxhighlight>
 
Sample output :
Line 680 ⟶ 769:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">a = ["one", "two", "three"]
println[random[a]]</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
random
 
mda(0) = {0,1,2,3,4,5,6,7,8,9}
 
print mda(rnd(10)-1)
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/ You can run this code. Copy the code, click this link, paste it in and press 'Run !']'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
 
Print sList[Rand(0, 11)]
 
End </langsyntaxhighlight>
Output:
<pre>
Line 697 ⟶ 797:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">a := [2, 9, 4, 7, 5, 3];
Random(a);</langsyntaxhighlight>
 
This works with many GAP objects, for instance groups:
 
<langsyntaxhighlight lang="gap">Random(SymmetricGroup(20));
 
(1,4,8,2)(3,12)(5,14,10,18,17,7,16)(9,13)(11,15,20,19)</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 720 ⟶ 820:
rand.Seed(time.Now().UnixNano())
fmt.Println(list[rand.Intn(len(list))])
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def list = [25, 30, 1, 450, 3, 78]
def random = new Random();
 
Line 730 ⟶ 830:
def i = random.nextInt(list.size())
println "list[${i}] == ${list[i]}"
}</langsyntaxhighlight>
 
{{out}}
Line 739 ⟶ 839:
 
Alternate Solution:
<langsyntaxhighlight lang="groovy">
[25, 30, 1, 450, 3, 78].sort{new Random()}?.take(1)[0]
</syntaxhighlight>
</lang>
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="gwbasic">10 RANDOMIZE TIMER : REM set random number seed to something arbitrary
20 DIM ARR(10) : REM initialise array
30 FOR I = 1 TO 10
Line 750 ⟶ 850:
50 NEXT I
60 C = 1 + INT(RND*10) : REM get a random index from 1 to 10 inclusive
70 PRINT ARR(C)</langsyntaxhighlight>
{{out}}<pre> 81</pre>
 
=={{header|Hare}}==
<syntaxhighlight lang="hare">use fmt;
use math::random;
use datetime;
 
export fn main() void = {
const array = ["one", "two", "three", "four", "five"];
const seed = datetime::now();
const seed = datetime::nsec(&seed);
let r = math::random::init(seed: u32);
 
fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!;
};</syntaxhighlight>
 
=={{header|Haskell}}==
Creating a custom function:
 
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
 
pick :: [a] -> IO a
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)
 
x <- pick [1, 2, 3]</langsyntaxhighlight>
 
Using the random-fu library:
 
<langsyntaxhighlight lang="haskell">import Data.Random
sample $ randomElement [1, 2, 3]</langsyntaxhighlight>
 
For example:
<langsyntaxhighlight lang="haskell">do
x <- sample $ randomElement [1, 2, 3]
print x</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The unary operator '?' selects a random element from its argument which may be a string, list, table, or set.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
L := [1,2,3] # a list
x := ?L # random element
end</langsyntaxhighlight>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(rand-pick (range 100))
</syntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> ({~ ?@#) 'abcdef'
b</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">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</langsyntaxhighlight>
 
For a List object rather than an array, substitute <code>list.get(...)</code> for <code>array[...]</code>. If preserving the order of the List isn't important, you could call <code>Collections.shuffle(list);</code> and then <code>list.get(0);</code>. You would need to shuffle each time unless you <code>remove</code>d the item from the list.
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE pick_random == dup size rand swap rem at.
 
(* initialize random number generator *)
time 89 * clock + srand
 
["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve"]
pick_random.</syntaxhighlight>
 
=={{header|jq}}==
Line 804 ⟶ 933:
to define one if an external source of entropy is available. In this entry, `/dev/urandom`
is used like so:
<langsyntaxhighlight lang="sh">< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq"># Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
Line 816 ⟶ 945:
 
# An illustration - 10 selections at random with replacement:
range(0;10) | ["a", "b", "c"] | .[length|prn]</langsyntaxhighlight>
{{out}}
<pre>
Line 823 ⟶ 952:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">array = [1,2,3]
rand(array)</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> 1?"abcdefg"
,"e"</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:pickran len rand * 1 + get ;
Line 839 ⟶ 968:
10 [drop pickran ?] for
 
" " input</langsyntaxhighlight>
{{out}}
<pre>("nest", "list")
Line 853 ⟶ 982:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import java.util.Random
Line 882 ⟶ 1,011:
println("\nA randomly selected element from the list is ${list.getRandomElement()}")
println("\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}")
}</langsyntaxhighlight>
 
Sample output:
Line 899 ⟶ 1,028:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
my array = array('one', 'two', 3)
)
 
#myarray -> get(integer_random(#myarray -> size, 1))</langsyntaxhighlight>
 
-> two
Line 909 ⟶ 1,038:
=={{header|Liberty BASIC}}==
The natural way to hold an array of text is in a space- or comma-delimited string, although an array could be used.
<langsyntaxhighlight lang="lb">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, " ")</langsyntaxhighlight>
Selecting term 5 in the list, which was Peter
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put "Apple,Banana,Peach,Apricot,Pear" into fruits
put item (random(the number of items of fruits)) of fruits</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<syntaxhighlight lang ="logo">pick [1 2 3]</langsyntaxhighlight>
 
=={{header|Lua}}==
 
<langsyntaxhighlight lang="lua">math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)])</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]:
randomNum := rand(1 ..numelems(a)):
a[randomNum()];</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">RandomChoice[{a, b, c}]</langsyntaxhighlight>
{{out}}
<pre>c</pre>
Line 940 ⟶ 1,069:
=={{header|MATLAB}} / {{header|Octave}}==
In case list is a cell array:
<langsyntaxhighlight Matlablang="matlab"> list = {'a','b','c'};
list{ceil(rand(1)*length(list))}</langsyntaxhighlight>
 
If list is a vector:
<langsyntaxhighlight Matlablang="matlab"> list = 1:1000;
list(ceil(rand(1)*length(list)))</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">random_element(l):= part(l, 1+random(length(l)));
/* (%i1) random_element(['a, 'b, 'c]);
(%o1) c
*/</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">0 П0 1 П1 2 П2 3 П3 4 П4 5
 
^ СЧ * [x] ПE КИПE С/П</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.Util
list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
println list[new(Random).getInt(len(list))]</langsyntaxhighlight>
 
{{out}}
Line 967 ⟶ 1,096:
 
=={{header|NetLogo}}==
<langsyntaxhighlight NetLogolang="netlogo">;; 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) )</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 986 ⟶ 1,115:
 
say v1 v2 v3
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (pick-random-element R)
(nth (rand (length R)) R))
</syntaxhighlight>
</lang>
Example:
<pre>
Line 1,003 ⟶ 1,132:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import random
randomize()
 
let ls = @["foo", "bar", "baz"]
echo sample(ls)</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">values := [1, 2, 3];
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];</langsyntaxhighlight>
 
=={{header|OCaml}}==
With a list:
<langsyntaxhighlight lang="ocaml">let list_rand lst =
let len = List.length lst in
List.nth lst (Random.int len)</langsyntaxhighlight>
 
<pre>
Line 1,025 ⟶ 1,154:
 
With an array:
<langsyntaxhighlight lang="ocaml">let array_rand ary =
let len = Array.length ary in
ary.(Random.int len)</langsyntaxhighlight>
 
<pre>
Line 1,033 ⟶ 1,162:
- : int = 3
</pre>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:fmt"
import "core:math/rand"
 
main :: proc() {
list := []string{"foo", "bar", "baz"}
rand_index := rand.int_max(len(list))
fmt.println(list[rand_index])
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: pickRand(l) l size rand l at ;</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(import (otus random!))
 
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pick(v)=v[random(#v)+1]</langsyntaxhighlight>
 
=={{header|Pascal}} / {{header|Delphi}} / {{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">Program PickRandomElement (output);
 
const
Line 1,058 ⟶ 1,200:
randomize;
writeln(s[low(s) + random(length(s))]);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @array = qw(a b c);
print $array[ rand @array ];</langsyntaxhighlight>
 
=={{header|Phix}}==
You can randomly pick an integer, float, string, [nested] subsequence, or anything else, just as easily from a mixed list as from a single-type list.
<lang Phix>constant s = {'a','b','c'}
<!--<syntaxhighlight lang="phix">(phixonline)-->
puts(1,s[rand(length(s))])</lang>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2.5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"three"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"4 as well"</span><span style="color: #0000FF;">}}}</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))])</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
 
% single element
println(choice=choice(10)), % single element
 
% From a list of numbers
L = 1..10,
println([choice(L) : _ in 1..10]),
 
% From a string
S = "pickrandomelement",
println([choice(S) : _ in 1..10]),
nl.
 
% Pick a random number from 1..N
choice(N) = random(1,N), integer(N) => true.
 
% Pick a random element from a list L.
choice(List) = List[choice(List.length)], list(List) => true.</syntaxhighlight>
 
{{out}}
<pre>choice = 4
[7,8,6,4,6,7,3,10,2,3]
ekcealmnei</pre>
 
This is a more structured output.
{{trans|Ada}}
<syntaxhighlight lang="picat">go2 =>
_ = random2(),
Vowels = "aeiou",
Consonants = "tnshrdl",
Specials = ",.?!",
RandWords = [( [[Consonants.choice()] ++ [Vowels.choice()] : _ in 1..10]
++ [Specials.choice()]
).flatten()
: _ in 1..3] ,
println(RandWords),
nl.</syntaxhighlight>
 
{{out}}
<pre>[dodidosisahuhiretesi,,loledohusoluhusululu?,tunuridunoheditonudu!]</pre>
 
 
Get the random elements from a frequency table (converted to a "Roulette wheel").
<syntaxhighlight lang="picat">% Pick according to a frequency table
go3 =>
_ = random2(),
Max = 17,
S = letter_freq_wheel(),
foreach(_ in 1..10)
println([choice(S) : _ in 1..1+choice(Max)])
end,
nl.
 
% Frequencies of letters converted to a "roulette wheel".
letter_freq_wheel = Chars =>
Freq =
[ [e,12.02],[t,9.10],[a,8.12],[o,7.68],[i,7.31],[n,6.95],[s,6.28],
[r,6.02],[h,5.92],[d,4.32],[l,3.98],[u,2.88],[c,2.71],[m,2.61],
[f,2.30],[y,2.11],[w,2.09],[g,2.03],[p,1.82],[b,1.49],[v,1.11],
[k,0.69],[x,0.17],[q,0.11],[j,0.10],[z,0.07]
],
Chars = [],
foreach([C,F] in Freq)
Chars := Chars ++ [C : _ in 1..ceiling(10*F)]
end,
nl.</syntaxhighlight>
 
{{out}}
<pre>ihvuotpswieecanrv
gnelhlutnopytoss
aentkttnenb
cnyawephc
nsioetohasedd
yapaeofyt
setmtoorwloiar
nsssrkcfgnpadtifln
rrlwree
nawmtnie</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(get Lst (rand 1 (length Lst)))</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> declare t(0:9) character (1) static initial
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
put ( t(10*random()) );</langsyntaxhighlight>
{{out}}
<pre>
Line 1,087 ⟶ 1,314:
Powershell has Get-Random Cmdlet which one of its overload is to select randomly from a given list
 
<syntaxhighlight lang="powershell">
<lang Powershell>
1..100 | Get-Random -Count 3
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).
M = i.
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s pickRandomElement(List source.s())
Protected x = ListSize(source())
Line 1,139 ⟶ 1,366:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten
Line 1,145 ⟶ 1,372:
Random picks from list: Seven Nine Two Six Four Four Nine Three Six Two</pre>
===Easy version===
<langsyntaxhighlight lang="purebasic">OpenConsole()
 
a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+
Line 1,155 ⟶ 1,382:
Print(StringField(a$,Random(CountString(a$,#TAB$),1),#TAB$)+#TAB$)
Next
Input()</langsyntaxhighlight>
{{out}}
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten
Line 1,161 ⟶ 1,388:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'</langsyntaxhighlight>
 
=={{header|Quackery}}==
<langsyntaxhighlight lang="quackery"> [ dup size random peek ] is pick ( [ --> x )
 
randomise
' [ 20 33 -15 7 0 ] pick echo cr
' pick pick echo</langsyntaxhighlight> <!-- just to make the point that data and code are not differentiated -->
{{out}}
<pre>
Line 1,178 ⟶ 1,405:
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus"># 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"
Line 1,189 ⟶ 1,416:
# picking some elements with repetition, and concatenating to get a word
paste(sample(letters, 10, rep=T), collapse="")
# [1] "episxgcgmt"</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (pick-item l)
(list-ref l (random (length l))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,204 ⟶ 1,431:
In a nutshell, picking an element from a list
is implemented with a method conveniently called "pick":
<syntaxhighlight lang="raku" perl6line>say (1, 2, 3).pick;</langsyntaxhighlight>
 
There are various ways of doing something similar, though.
Line 1,212 ⟶ 1,439:
 
Selection with replacement: (roll of a die)
<syntaxhighlight lang="raku" perl6line>say (1..6).roll; # return 1 random value in the range 1 through 6
say (1..6).roll(3); # return a list of 3 random values in the range 1 through 6
say (1..6).roll(*)[^100]; # return first 100 values from a lazy infinite list of random values in the range 1 through 6</langsyntaxhighlight>
 
Selection without replacement: (pick a card from a deck)
<syntaxhighlight lang="raku" perl6line># define the deck
my @deck = <2 3 4 5 6 7 8 9 J Q K A> X~ <♠ ♣ ♥ ♦>;
say @deck.pick; # Pick a card
say @deck.pick(5); # Draw 5
say @deck.pick(*); # Get a shuffled deck</langsyntaxhighlight>
Or you can always use the normal <tt>rand</tt> built-in
to generate a subscript (which automatically truncates any fractional part):
<syntaxhighlight lang="raku" perl6line>@array[@array * rand]</langsyntaxhighlight>
However, the <tt>pick</tt> and <tt>roll</tt> 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:
<syntaxhighlight lang="raku" perl6line>say Bool.pick; # returns either True or False</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">>> random/only collect [repeat i 10 [keep i]]</langsyntaxhighlight>
 
=={{header|ReScript}}==
<langsyntaxhighlight ReScriptlang="rescript">let fruits = ["apple", "banana", "coconut", "orange", "lychee"]
 
let pickRand = arr => {
Line 1,242 ⟶ 1,469:
}
 
Js.log(pickRand(fruits))</langsyntaxhighlight>
{{out}}
<pre>$ bsc pickrand.res > pickrand.bs.js
Line 1,254 ⟶ 1,481:
 
Also, the newly named elements have been incorporated into this table.
<langsyntaxhighlight lang="rexx">/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/
l= "Hydrogen_H Helium_He Lithium_Li Beryllium_Be Boron_B"
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium'
l=l "Carbon_C Nitrogen_N Oxygen_O Fluorine_F Neon_Ne Sodium_Na"
_=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium'
l=l "Magnesium_Mg Aluminium_Al Silicon_Si Phosphorus_P Sulfur_S"
_=_ 'scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium'
l=l "Chlorine_Cl Argon_Ar Potassium_K Calcium_Ca Scandium_Sc"
_=_ 'germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium'
l=l "Titanium_Ti Vanadium_V Chromium_Cr Manganese_Mn Iron_Fe"
_=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin'
l=l "Cobalt_Co Nickel_Ni Copper_Cu Zinc_Zn Gallium_Ga"
_=_ 'antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium'
l=l "Germanium_Ge Arsenic_As Selenium_Se Bromine_Br Krypton_Kr"
_=_ 'neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium'
l=l "Rubidium_Rb Strontium_Sr Yttrium_Y Zirconium_Zr Niobium_Nb"
_=_ 'thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum'
l=l "Molybdenum_Mo Technetium_Tc Ruthenium_Ru Rhodium_Rh"
_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium radium actinium'
l=l "Palladium_Pd Silver_Ag Cadmium_Cd Indium_In Tin_Sn"
_=_ 'thorium protactinium uranium neptunium plutonium americium curium berkelium'
l=l "Antimony_Sb Tellurium_Te Iodine_I Xenon_Xe Caesium_Cs"
_=_ 'californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium'
l=l "Barium_Ba Lanthanum_La Cerium_Ce Praseodymium_Pr"
_=_ 'seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium'
l=l "Neodymium_Nd Promethium_Pm Samarium_Sm Europium_Eu"
_=_ 'flerovium moscovium livermorium tennessine oganesson ununenniym unbinvlium umbiunium'
l=l "Gadolinium_Gd Terbium_Tb Dysprosium_Dy Holmium_Ho Erbium_Er"
l=l "Thulium_Tm Ytterbium_Yb Lutetium_Lu Hafnium_Hf Tantalum_Ta"
l=l "Tungsten_W Rhenium_Re Osmium_Os Iridium_Ir Platinum_Pt"
l=l "Gold_Au Mercury_Hg Thallium_Tl Lead_Pb Bismuth_Bi"
l=l "Polonium_Po Astatine_At Radon_Rn Francium_Fr Radium_Ra"
l=l "Actinium_Ac Thorium_Th Protactinium_Pa Uranium_U"
l=l "Neptunium_Np Plutonium_Pu Americium_Am Curium_Cm"
l=l "Berkelium_Bk Californium_Cf Einsteinium_Es Fermium_Fm"
l=l "Mendelevium_Md Nobelium_No Lawrencium_Lr Rutherfordium_Rf"
l=l "Dubnium_Db Seaborgium_Sg Bohrium_Bh Hassium_Hs Meitnerium_Mt"
l=l "Darmstadtium_Ds Roentgenium_Rg Copernicium_Cn Nihonium_Nh"
l=l "Flerovium_Fl Moscovium_Mc Livermorium_Lv Tennessine_Ts"
l=l "Oganesson_Og Ununbium_Uub Ununtrium_Uut Ununquadium_Uuq"
n=words(l) /* Number of known elements */
/*----- You can't trust atoms, -----*/
/*----- they make everything up. -----*/
Parse Arg pick /* atomic number specified */
If pick>n Then Do
Say 'Element' pick 'hasn''t been discovered by now'
Exit
End
take=pick
If pick='' Then
take=random(1,n)
 
item=word(l,take) /*pick the specified or random element */
/*───── You can't trust atoms, ─────*/
Parse Var item name '_' symbol
/*───── they make everything up. ─────*/
If pick='' Then
which='Random'
Else
which='Specified'
Say which 'element: ' take name '('symbol')' /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
<pre>E:\>rexx pez
Random element: 100 Fermium (Fm)
 
E:\>rexx pez 8
#= words(_) /*obtain the number of words in list. */
Specified element: 8 Oxygen (O)
item= word(_, random(1, #) ) /*pick a random word (element) in list.*/
 
say 'random element: ' item /*stick a fork in it, we're all done. */</lang>
E:\>rexx pez 133
{{out|output}}
Element 133 hasn't been discovered by now</pre>
<pre>
random element: tennessine
</pre>
 
===version 2===
Line 1,285 ⟶ 1,542:
<br>smaller limit of the total length of a clause, in particular PC/REXX and Personal REXX
<br>which have a limit of 1,000 characters).
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* 18.10.2012 Walter Pachl Not only the list of elements shortened:-)
Line 1,295 ⟶ 1,552:
Say word(wl,random(1,words(wl)))
</syntaxhighlight>
</lang>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = "abcdefghij"
for i = 1 to 10
Line 1,306 ⟶ 1,563:
ok
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
≪ DUP SIZE RAND * CEIL GET ≫ ‘<span style="color:blue">RANDGET</span>’ STO
 
{ Alpha Beta Gamma Delta } <span style="color:blue">RANDGET</span>
{ Alpha Beta Gamma Delta } <span style="color:blue">RANDGET</span>
{ Alpha Beta Gamma Delta } <span style="color:blue">RANDGET</span>
{{out}}
<pre>
3: ‘Delta’
2: ‘Alpha’
1: ‘Beta’
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
%w(north east south west).sample # => "west"
(1..100).to_a.sample(2) # => [17, 79]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">list$ = "a,b,c,d,e,f,g,h,i,j"
letter = rnd(1) * 10
print "Selected letter:"; word$(list$,letter,",")</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
use rand::Rng;
Line 1,329 ⟶ 1,599:
println!("{}", rng.choose(&array).unwrap());
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">val a = (1 to 10).toList
 
println(scala.util.Random.shuffle(a).head)</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
begin
writeln(rand([] ("foo", "bar", "baz")));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = %w(north east south west);
say arr.rand;
say arr.rand(2).dump;</langsyntaxhighlight>
{{out}}
<pre>south
Line 1,354 ⟶ 1,624:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">x := #(1 2 3) atRandom.</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang SuperCollider="supercollider">[1, 2, 3].choose</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Darwin
 
let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 1,369 ⟶ 1,639:
(for selection of an item from a list) and the pattern for generating an integral random number from the range <math>[0,n)</math>.
It's simpler to use when wrapped up as a helper procedure:
<langsyntaxhighlight lang="tcl">proc randelem {list} {
lindex $list [expr {int(rand()*[llength $list])}]
}
set x [randelem {1 2 3 4 5}]</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ 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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,389 ⟶ 1,659:
{{trans|Tcl}}
 
<langsyntaxhighlight lang="txr">@(do (defun randelem (seq)
[seq (random nil (length seq))]))
@(bind x @(randelem #("a" "b" "c" "d")))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell}}
<langsyntaxhighlight lang="sh">list=(these are some words)
printf '%s\n' "${list[RANDOM%${#list[@]}]}"</langsyntaxhighlight>
 
{{works with|Zsh}}
<langsyntaxhighlight lang="sh">list=(these are some words)
printf '%s\n' "$list[RANDOM%$#list+1]"</langsyntaxhighlight>
 
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa"># 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</langsyntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 1,424 ⟶ 1,694:
Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">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"))</langsyntaxhighlight>
 
{{Out}}
Line 1,439 ⟶ 1,709:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Program
Sub Main()
Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
Line 1,446 ⟶ 1,716:
Console.WriteLine("I picked element {0}", randomElement)
End Sub
End Module</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import rand
 
fn main() {
list := ["friends", "peace", "people", "happiness", "hello", "world"]
for index in 1..list.len + 1 {println(index.str() + ': ' + list[rand.intn(list.len) or {}])}
}</syntaxhighlight>
 
{{out}}
Sample of random output:
<pre>
1: peace
2: happiness
3: hello
4: friends
5: peace
6: people
</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var rand = Random.new()
var colors = ["red", "green", "blue", "yellow", "pink"]
for (i in 0..4) System.print(colors[rand.int(colors.count)])</langsyntaxhighlight>
 
{{out}}
Line 1,466 ⟶ 1,755:
 
=={{header|XBS}}==
<langsyntaxhighlight XBSlang="xbs">set Array = ["Hello","World",1,2,3];
log(Array[rnd(0,?Array-1)]);</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, Text=12;
int List;
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX)
Text(0, List(Ran(5)));
]</langsyntaxhighlight>
 
=={{header|Zig}}==
This example uses the [http://www.pcg-random.org/ PCG] algorithm.
 
<langsyntaxhighlight lang="zig">const std = @import("std");
 
const debug = std.debug;
Line 1,508 ⟶ 1,797:
 
debug.warn("\n", .{});
}</langsyntaxhighlight>
 
{{out}}
Line 1,524 ⟶ 1,813:
=={{header|zkl}}==
{{trans|XPL0}}
<langsyntaxhighlight lang="zkl">list:=T("hydrogen", "helium", "lithium", "beryllium", "boron");
list[(0).random(list.len())]</langsyntaxhighlight>
1,973

edits