Pick random element
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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
<lang Lisp>:set-state-ok t
(defun pick-random-element (xs state)
(mv-let (idx state) (random$ (len xs) state) (mv (nth idx xs) state)))</lang>
Ada
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.
<lang Ada>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;</lang>
Sample Output:
horanohesuhodinahiru. desehonirosedisinelo, losihehederidonolahe?
Aime
<lang aime>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');</lang>
AutoHotkey
- True Arrays
<lang AHK>list := ["abc", "def", "gh", "ijklmnop", "hello", "world"] Random, randint, 1, % list.MaxIndex() MsgBox % List[randint]</lang>
- Pseudo-Arrays
<lang AutoHotkey>list := "abc,def,gh,ijklmnop,hello,world" StringSplit list, list, `, Random, randint, 1, %list0% MsgBox % List%randint%</lang>
Bash
<lang Bash># 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"</lang>
BASIC
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)
.)
<lang qbasic>'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)</lang>
See also: Liberty BASIC, PureBasic, Run BASIC
C
<lang C>#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;
}</lang>
C#
<lang csharp>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); }
}</lang>
Clojure
<lang Clojure>(let [l '(\c \l \o \j \u \r \e)]
(println (nth l (rand-int (count l)))))</lang>
CoffeeScript
<lang coffeescript>array = [1,2,3] console.log array[Math.floor(Math.random() * array.length)]</lang>
D
<lang d>import std.stdio, std.random;
void main() {
auto items = ["foo", "bar", "baz"]; auto r = items[uniform(0, $)]; writeln(r);
}</lang>
Euphoria
<lang euphoria>constant s = {'a', 'b', 'c'} puts(1,s[rand($)])</lang>
Factor
<lang factor>( scratchpad ) { "a" "b" "c" "d" "e" "f" } random . "a"</lang>
Go
<lang go>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))])
}</lang>
Haskell
Creating a custom function:
<lang haskell>import Random (randomRIO)
pick :: [a] -> IO a pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)
x <- pick [1 2 3]</lang>
Using the random-extras library:
<lang haskell>import Data.Random import Data.Random.Source.DevRandom import Data.Random.Extras
x <- runRVar (choice [1 2 3]) DevRandom</lang>
Icon and Unicon
The unary operator '?' selects a random element from its argument which may be a string, list, table, or set.
<lang Icon>procedure main()
L := [1,2,3] # a list x := ?L # random element
end</lang>
J
<lang j> ({~ ?@#) 'abcdef' b</lang>
Java
<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</lang>
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 remove
d the item from the list.
JavaScript
<lang javascript>var array = [1,2,3]; return array[Math.floor(Math.random() * array.length)];</lang>
K
<lang K> 1?"abcdefg" ,"e"</lang>
LabVIEW
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.
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. <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, " ")</lang>
Selecting term 5 in the list, which was Peter
Logo
<lang logo>pick [1 2 3]</lang>
Lua
<lang lua>math.randomseed(os.time()) local a = {1,2,3} print(a[math.random(1,#a)])</lang>
Mathematica
<lang Mathematica>RandomChoice[{a, b, c}] ->c</lang>
MATLAB / Octave
In case list is a cell array: <lang Matlab> list = {'a','b','c'}; list{ceil(rand(1)*length(list))}</lang>
If list is a vector: <lang Matlab> list = 1:1000; list(ceil(rand(1)*length(list)))</lang>
NetLogo
<lang 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) )</lang>
Objeck
<lang objeck>values := [1, 2, 3]; value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];</lang>
OCaml
With a list: <lang ocaml>let list_rand lst =
let len = List.length lst in List.nth lst (Random.int len)</lang>
# list_rand [1;2;3;4;5] ;; - : int = 3
With an array: <lang ocaml>let array_rand ary =
let len = Array.length ary in ary.(Random.int len)</lang>
# array_rand [|1;2;3;4;5|] ;; - : int = 3
PARI/GP
<lang parigp>pick(v)=v[random(#v)+1]</lang>
Pascal
<lang pascal>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.</lang>
Perl
<lang perl>my @array = ('a', 'b', 'c'); print $array[ rand @array ];</lang>
Perl 6
Perl 6 has two functions to return random elements depending on whether you are doing selection with or without replacement.
Selection with replacement: (roll of a die) <lang perl6>(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</lang>
Selection without replacement: (pick a card from a deck) <lang perl6>( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick; # Pick a card ( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick(5); # Draw 5 ( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick(*); # Get a shuffled deck</lang>
PHP
<lang php>$arr = array('foo', 'bar', 'baz'); $x = $arr[array_rand($arr)];</lang>
PicoLisp
<lang PicoLisp>(get Lst (rand 1 (length Lst)))</lang>
PL/I
<lang PL/I> declare t(0:9) character (1) static initial
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); put ( t(10*random()) );</lang>
output:
e
PureBasic
<lang PureBasic>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</lang> Sample 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
Python
<lang python>>>> import random >>> random.choice(['foo', 'bar', 'baz']) 'baz'</lang>
R
<lang r># 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"</lang>
REXX
This REXX example takes the task very literally. <lang rexx>/*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 califonium einsteinum fermium mendelevium' _=_ 'nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium' _=_ 'meitnerium darmstadtium roentgenium copernicium Ununtrium'
w=words(_) say 'random element =' subword(_,random(1,w),1)</lang> output
random element = ytterbium
Ruby
<lang ruby>irb(main):001:0> %w(north east south west).sample => "west" irb(main):002:0> (1..100).to_a.sample(2) => [17, 79]</lang>
<lang ruby>irb(main):001:0> %w(north east south west).choice => "south"</lang>
Run BASIC
<lang runbasic>list$ = "a,b,c,d,e,f,g,h,i,j" letter = rnd(1) * 10 print "Selected letter:"; word$(list$,letter,",")</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
begin writeln(rand([] ("foo", "bar", "baz"))); end func;</lang>
Smalltalk
<lang smalltalk>x := #(1 2 3) atRandom.</lang>
Tcl
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:
<lang tcl>proc randelem {list} {
lindex $list [expr {int(rand()*[llength $list])}]
} set x [randelem {1 2 3 4 5}]</lang>
TXR
<lang txr>@(do (defun randelem (vec)
(vecref vec (random nil (length vec)))))
@(bind x @(randelem #("a" "b" "c" "d")))</lang>
TUSCRIPT
<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</lang> Output:
Selecting term 3 in the list, which was George
- Programming Tasks
- Basic language learning
- ACL2
- Ada
- Aime
- AutoHotkey
- Bash
- BASIC
- C
- C sharp
- Clojure
- CoffeeScript
- D
- Euphoria
- Factor
- Go
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- K
- LabVIEW
- Liberty BASIC
- Logo
- Lua
- Mathematica
- MATLAB
- Octave
- NetLogo
- Objeck
- OCaml
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PureBasic
- Python
- R
- REXX
- Ruby
- Run BASIC
- Seed7
- Smalltalk
- Tcl
- TXR
- TUSCRIPT
- Randomness