Pick random element: Difference between revisions
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
|||
Line 6: | Line 6: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">print(random:choice([‘foo’, ‘bar’, ‘baz’]))</syntaxhighlight> |
||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
Line 12: | Line 12: | ||
For brevity's sake, the implementations of the RNG and printing routines were left out; they can be provided if requested. |
For brevity's sake, the implementations of the RNG and printing routines were left out; they can be provided if requested. |
||
< |
<syntaxhighlight lang="asm"> .model small |
||
.stack 1024 |
.stack 1024 |
||
Line 41: | Line 41: | ||
mov ax,4C00h |
mov ax,4C00h |
||
int 21h ;exit program and return to MS-DOS |
int 21h ;exit program and return to MS-DOS |
||
end start</ |
end start</syntaxhighlight> |
||
Line 54: | Line 54: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">:set-state-ok t |
||
(defun pick-random-element (xs state) |
(defun pick-random-element (xs state) |
||
(mv-let (idx state) |
(mv-let (idx state) |
||
(random$ (len xs) state) |
(random$ (len xs) state) |
||
(mv (nth idx xs) state)))</ |
(mv (nth idx xs) state)))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
DEFINE PTR="CARD" |
DEFINE PTR="CARD" |
||
PTR ARRAY a(7) |
PTR ARRAY a(7) |
||
Line 80: | Line 80: | ||
PrintE(a(index)) |
PrintE(a(index)) |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pick_random_element.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pick_random_element.png Screenshot from Atari 8-bit computer] |
||
Line 112: | Line 112: | ||
resp. a list of consonants. |
resp. a list of consonants. |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Numerics.Float_Random; |
||
procedure Pick_Random_Element is |
procedure Pick_Random_Element is |
||
Line 141: | Line 141: | ||
end loop; |
end loop; |
||
Ada.Text_IO.New_Line; |
Ada.Text_IO.New_Line; |
||
end Pick_Random_Element;</ |
end Pick_Random_Element;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 147: | Line 147: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">list l; |
||
l_append(l, 'a'); |
l_append(l, 'a'); |
||
Line 157: | Line 157: | ||
o_byte(l[drand(5)]); |
o_byte(l[drand(5)]); |
||
o_byte('\n');</ |
o_byte('\n');</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
||
< |
<syntaxhighlight lang="algol68"># pick a random element from an array of strings # |
||
OP PICKRANDOM = ( []STRING list )STRING: |
OP PICKRANDOM = ( []STRING list )STRING: |
||
Line 183: | Line 183: | ||
print( ( PICKRANDOM days, newline ) ) |
print( ( PICKRANDOM days, newline ) ) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 191: | Line 191: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|Dyalog APL}} |
{{works with|Dyalog APL}} |
||
<lang |
<syntaxhighlight lang="apl">pickRandom ← (?≢)⊃⊢</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> pickRandom 'ABCDE' |
<pre> pickRandom 'ABCDE' |
||
Line 205: | Line 205: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"two"</pre> |
<pre>"two"</pre> |
||
Line 211: | Line 211: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">fruit: ["apple" "banana" "pineapple" "apricot" "watermelon"] |
||
print sample fruit</ |
print sample fruit</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 222: | Line 222: | ||
; True Arrays |
; True Arrays |
||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
< |
<syntaxhighlight lang="ahk">list := ["abc", "def", "gh", "ijklmnop", "hello", "world"] |
||
Random, randint, 1, % list.MaxIndex() |
Random, randint, 1, % list.MaxIndex() |
||
MsgBox % List[randint]</ |
MsgBox % List[randint]</syntaxhighlight> |
||
; Pseudo-Arrays |
; Pseudo-Arrays |
||
{{works with|AutoHotkey_Basic}} |
{{works with|AutoHotkey_Basic}} |
||
< |
<syntaxhighlight lang="autohotkey">list := "abc,def,gh,ijklmnop,hello,world" |
||
StringSplit list, list, `, |
StringSplit list, list, `, |
||
Random, randint, 1, %list0% |
Random, randint, 1, %list0% |
||
MsgBox % List%randint%</ |
MsgBox % List%randint%</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk"># syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK |
||
BEGIN { |
BEGIN { |
||
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",") |
n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",") |
||
Line 240: | Line 240: | ||
printf("%s\n",day_of_week[x]) |
printf("%s\n",day_of_week[x]) |
||
exit(0) |
exit(0) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>GAWK -f PICK_RANDOM_ELEMENT.AWK |
<pre>GAWK -f PICK_RANDOM_ELEMENT.AWK |
||
Line 254: | 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. |
This is simply an application of a ranged random number used as an array index. '''BaCon''' has no built in random element selector. |
||
< |
<syntaxhighlight lang="freebasic">' Pick random element |
||
OPTION BASE 1 |
OPTION BASE 1 |
||
DECLARE words$[6] |
DECLARE words$[6] |
||
Line 261: | Line 261: | ||
element = RANDOM(6) + 1 |
element = RANDOM(6) + 1 |
||
PRINT "Chose ", element, ": ", words$[element]</ |
PRINT "Chose ", element, ": ", words$[element]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 272: | Line 272: | ||
=={{header|Bash}}== |
=={{header|Bash}}== |
||
< |
<syntaxhighlight lang="bash"># borrowed from github.com/search?q=bashnative |
||
rand() { |
rand() { |
||
Line 283: | Line 283: | ||
} |
} |
||
echo "You feel like a $(rand_element pig donkey unicorn eagle) today"</ |
echo "You feel like a $(rand_element pig donkey unicorn eagle) today"</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 291: | 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>.) |
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>.) |
||
< |
<syntaxhighlight lang="qbasic">'setup |
||
DIM foo(10) AS LONG |
DIM foo(10) AS LONG |
||
DIM n AS LONG, x AS LONG |
DIM n AS LONG, x AS LONG |
||
Line 303: | Line 303: | ||
'output |
'output |
||
PRINT x, foo(x)</ |
PRINT x, foo(x)</syntaxhighlight> |
||
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#Run BASIC|Run BASIC]] |
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#Run BASIC|Run BASIC]] |
||
==={{header|Applesoft 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. |
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 |
20 FOR I = 0 TO 9: READ A$(I): NEXT |
||
25 TI = PEEK(78) + PEEK(79)*256 |
25 TI = PEEK(78) + PEEK(79)*256 |
||
Line 317: | Line 317: | ||
100 DATAALPHA, BRAVO, CHARLIE, DELTA, ECHO |
100 DATAALPHA, BRAVO, CHARLIE, DELTA, ECHO |
||
110 DATAFOXTROT, GOLF, HOTEL, INDIA, JULIETT |
110 DATAFOXTROT, GOLF, HOTEL, INDIA, JULIETT |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
< |
<syntaxhighlight lang="qbasic">10 DIM A$(9) |
||
20 FOR I=0 TO 9 : READ A$(I) : NEXT |
20 FOR I=0 TO 9 : READ A$(I) : NEXT |
||
30 X = RND(-TI) : REM 'PLANT A RANDOM SEED' |
30 X = RND(-TI) : REM 'PLANT A RANDOM SEED' |
||
Line 326: | Line 326: | ||
60 END |
60 END |
||
100 DATA ALPHA, BRAVO, CHARLIE, DELTA, ECHO |
100 DATA ALPHA, BRAVO, CHARLIE, DELTA, ECHO |
||
110 DATA FOXTROT, GOLF, HOTEL, INDIA, JULIETT</ |
110 DATA FOXTROT, GOLF, HOTEL, INDIA, JULIETT</syntaxhighlight> |
||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
< |
<syntaxhighlight lang="basic256">dim a$ = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"} |
||
for i = 1 to 5 |
for i = 1 to 5 |
||
randInt = int(rand * 10) |
randInt = int(rand * 10) |
||
print a$[randInt] |
print a$[randInt] |
||
next i</ |
next i</syntaxhighlight> |
||
==={{header|True BASIC}}=== |
==={{header|True BASIC}}=== |
||
{{trans|QBasic}} |
{{trans|QBasic}} |
||
< |
<syntaxhighlight lang="qbasic">!setup |
||
DIM foo(10) |
DIM foo(10) |
||
FOR n = LBOUND(foo) TO UBOUND(foo) |
FOR n = LBOUND(foo) TO UBOUND(foo) |
||
Line 351: | Line 351: | ||
!output |
!output |
||
PRINT x, foo(x) |
PRINT x, foo(x) |
||
END</ |
END</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
< |
<syntaxhighlight lang="yabasic">dim a$(9) |
||
a$(0)="Zero" |
a$(0)="Zero" |
||
a$(1)="One" |
a$(1)="One" |
||
Line 370: | Line 370: | ||
randInt = int(ran(10)) |
randInt = int(ran(10)) |
||
print a$(randInt) |
print a$(randInt) |
||
next i</ |
next i</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Since there is no arrays in Batch File, I will use a 1-based pseudo-array. |
Since there is no arrays in Batch File, I will use a 1-based pseudo-array. |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 389: | Line 389: | ||
echo.!pseudo[%rndInt%]! |
echo.!pseudo[%rndInt%]! |
||
pause |
pause |
||
exit /b</ |
exit /b</syntaxhighlight> |
||
{{Out|Sample Outputs}} |
{{Out|Sample Outputs}} |
||
<pre>Delta |
<pre>Delta |
||
Line 404: | Line 404: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM list$(5) |
||
list$() = "The", "five", "boxing", "wizards", "jump", "quickly" |
list$() = "The", "five", "boxing", "wizards", "jump", "quickly" |
||
chosen% = RND(6) |
chosen% = RND(6) |
||
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'"</ |
PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 418: | Line 418: | ||
Both use BQN's system value <code>•rand</code>, which contains multiple functions for generating random values. |
Both use BQN's system value <code>•rand</code>, which contains multiple functions for generating random values. |
||
< |
<syntaxhighlight lang="bqn">PR ← {𝕩⊑˜•rand.Range ≠𝕩} |
||
PR1 ← •rand.Range∘≠⊸⊑</ |
PR1 ← •rand.Range∘≠⊸⊑</syntaxhighlight> |
||
{{Out|Usage}} |
{{Out|Usage}} |
||
< |
<syntaxhighlight lang="bqn"> PR 5‿67‿7‿23 |
||
67 |
67 |
||
PR1 5‿67‿7‿23 |
PR1 5‿67‿7‿23 |
||
7</ |
7</syntaxhighlight> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) "ABCDEFG"123456 0 6rn-]!! |
blsq ) "ABCDEFG"123456 0 6rn-]!! |
||
'G |
'G |
||
</syntaxhighlight> |
|||
</lang> |
|||
''123456'' is the random seed. In order to pick another element you have to change the random seed. |
''123456'' is the random seed. In order to pick another element you have to change the random seed. |
||
Line 437: | Line 437: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<syntaxhighlight lang="c"> |
|||
<lang c> |
|||
#include <stdio.h> |
#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 454: | Line 454: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
<pre> |
<pre> |
||
Line 491: | Line 491: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 501: | Line 501: | ||
Console.WriteLine("I picked element {0}", randomElement); |
Console.WriteLine("I picked element {0}", randomElement); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <random> |
#include <random> |
||
#include <vector> |
#include <vector> |
||
Line 518: | Line 518: | ||
<< " !\n" ; |
<< " !\n" ; |
||
return 0 ; |
return 0 ; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">import ceylon.random { |
||
DefaultRandom |
DefaultRandom |
||
Line 530: | Line 530: | ||
value element = random.nextElement([1, 2, 3, 4, 5, 6]); |
value element = random.nextElement([1, 2, 3, 4, 5, 6]); |
||
print(element); |
print(element); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
<lang |
<syntaxhighlight lang="clojure">(rand-nth coll)</syntaxhighlight> |
||
where <code>coll</code> is some sequential collection. Equivalent to: |
where <code>coll</code> is some sequential collection. Equivalent to: |
||
< |
<syntaxhighlight lang="clojure">(nth coll (rand-int (count coll)))</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">random_element = proc [T: type] (a: array[T]) returns (T) |
||
return(a[array[T]$low(a) + random$next(array[T]$size(a))]) |
return(a[array[T]$low(a) + random$next(array[T]$size(a))]) |
||
end random_element |
end random_element |
||
Line 554: | Line 554: | ||
stream$putl(po, random_element[string](arr)) |
stream$putl(po, random_element[string](arr)) |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>qux |
<pre>qux |
||
Line 564: | Line 564: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|GNU Cobol}} |
{{works with|GNU Cobol}} |
||
< |
<syntaxhighlight lang="cobol"> >>SOURCE FREE |
||
IDENTIFICATION DIVISION. |
IDENTIFICATION DIVISION. |
||
PROGRAM-ID. random-element. |
PROGRAM-ID. random-element. |
||
Line 579: | Line 579: | ||
DISPLAY nums (random-idx) |
DISPLAY nums (random-idx) |
||
. |
. |
||
END PROGRAM random-element.</ |
END PROGRAM random-element.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript">array = [1,2,3] |
||
console.log array[Math.floor(Math.random() * array.length)]</ |
console.log array[Math.floor(Math.random() * array.length)]</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight 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*)) |
(print (nth (random (length *list*)) *list*)) |
||
(print (nth (random (length *list*)) *list*))</ |
(print (nth (random (length *list*)) *list*))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 598: | Line 598: | ||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
puts [1, 2, 3, 4, 5].sample(1) |
puts [1, 2, 3, 4, 5].sample(1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.random; |
||
void main() { |
void main() { |
||
const items = ["foo", "bar", "baz"]; |
const items = ["foo", "bar", "baz"]; |
||
items[uniform(0, $)].writeln; |
items[uniform(0, $)].writeln; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 614: | Line 614: | ||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">!print choose [ "one" "two" "chicken" ]</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
< |
<syntaxhighlight lang="easyprog.online">ar$[] = [ "spring" "summer" "autumn" "winter" ] |
||
print ar$[random len ar$[]]</ |
print ar$[random len ar$[]]</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define (pick-random list) |
(define (pick-random list) |
||
(list-ref list (random (length list)))) |
(list-ref list (random (length list)))) |
||
(pick-random (iota 1000)) → 667 |
(pick-random (iota 1000)) → 667 |
||
(pick-random (iota 1000)) → 179 |
(pick-random (iota 1000)) → 179 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0 : |
ELENA 5.0 : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
extension listOp |
extension listOp |
||
Line 644: | Line 644: | ||
console.printLine("I picked element ",item.randomItem()) |
console.printLine("I picked element ",item.randomItem()) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{works with|Elixir|1.2}} |
{{works with|Elixir|1.2}} |
||
< |
<syntaxhighlight 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] |
[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) |
iex(2)> Enum.random(list) |
||
19 |
19 |
||
iex(3)> Enum.take_random(list,4) |
iex(3)> Enum.take_random(list,4) |
||
[19, 20, 7, 15]</ |
[19, 20, 7, 15]</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun random-choice (items) |
||
(nth (random (length items)) items)) |
(nth (random (length items)) items)) |
||
(random-choice '("a" "b" "c")) |
(random-choice '("a" "b" "c")) |
||
;; => "a"</ |
;; => "a"</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel |
||
-module(pick_random). |
-module(pick_random). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 671: | Line 671: | ||
Index = rand:uniform(length(List)), |
Index = rand:uniform(length(List)), |
||
lists:nth(Index,List). |
lists:nth(Index,List). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">constant s = {'a', 'b', 'c'} |
||
puts(1,s[rand($)])</ |
puts(1,s[rand($)])</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let list = ["a"; "b"; "c"; "d"; "e"] |
||
let rand = new System.Random() |
let rand = new System.Random() |
||
printfn "%s" list.[rand.Next(list.Length)]</ |
printfn "%s" list.[rand.Next(list.Length)]</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) { "a" "b" "c" "d" "e" "f" } random . |
||
"a"</ |
"a"</syntaxhighlight> |
||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
< |
<syntaxhighlight lang="falcon"> |
||
lst = [1, 3, 5, 8, 10] |
lst = [1, 3, 5, 8, 10] |
||
> randomPick(lst) |
> randomPick(lst) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program pick_random |
||
implicit none |
implicit none |
||
Line 704: | Line 704: | ||
call random_number(r) |
call random_number(r) |
||
write(*,*) a(int(r*size(a)) + 1) |
write(*,*) a(int(r*size(a)) + 1) |
||
end program</ |
end program</syntaxhighlight> |
||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
Line 710: | Line 710: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"} |
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"} |
||
Line 721: | Line 721: | ||
Print a(randInt) |
Print a(randInt) |
||
Next |
Next |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
Sample output : |
Sample output : |
||
Line 734: | Line 734: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink">a = ["one", "two", "three"] |
||
println[random[a]]</ |
println[random[a]]</syntaxhighlight> |
||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/ You can run this code. Copy the code, click this link, paste it in and press 'Run !']''' |
'''[https://gambas-playground.proko.eu/ You can run this code. Copy the code, click this link, paste it in and press 'Run !']''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] |
Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] |
||
Print sList[Rand(0, 11)] |
Print sList[Rand(0, 11)] |
||
End </ |
End </syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 751: | Line 751: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">a := [2, 9, 4, 7, 5, 3]; |
||
Random(a);</ |
Random(a);</syntaxhighlight> |
||
This works with many GAP objects, for instance groups: |
This works with many GAP objects, for instance groups: |
||
< |
<syntaxhighlight lang="gap">Random(SymmetricGroup(20)); |
||
(1,4,8,2)(3,12)(5,14,10,18,17,7,16)(9,13)(11,15,20,19)</ |
(1,4,8,2)(3,12)(5,14,10,18,17,7,16)(9,13)(11,15,20,19)</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 774: | Line 774: | ||
rand.Seed(time.Now().UnixNano()) |
rand.Seed(time.Now().UnixNano()) |
||
fmt.Println(list[rand.Intn(len(list))]) |
fmt.Println(list[rand.Intn(len(list))]) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def list = [25, 30, 1, 450, 3, 78] |
||
def random = new Random(); |
def random = new Random(); |
||
Line 784: | Line 784: | ||
def i = random.nextInt(list.size()) |
def i = random.nextInt(list.size()) |
||
println "list[${i}] == ${list[i]}" |
println "list[${i}] == ${list[i]}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 793: | Line 793: | ||
Alternate Solution: |
Alternate Solution: |
||
< |
<syntaxhighlight lang="groovy"> |
||
[25, 30, 1, 450, 3, 78].sort{new Random()}?.take(1)[0] |
[25, 30, 1, 450, 3, 78].sort{new Random()}?.take(1)[0] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
< |
<syntaxhighlight lang="gwbasic">10 RANDOMIZE TIMER : REM set random number seed to something arbitrary |
||
20 DIM ARR(10) : REM initialise array |
20 DIM ARR(10) : REM initialise array |
||
30 FOR I = 1 TO 10 |
30 FOR I = 1 TO 10 |
||
Line 804: | Line 804: | ||
50 NEXT I |
50 NEXT I |
||
60 C = 1 + INT(RND*10) : REM get a random index from 1 to 10 inclusive |
60 C = 1 + INT(RND*10) : REM get a random index from 1 to 10 inclusive |
||
70 PRINT ARR(C)</ |
70 PRINT ARR(C)</syntaxhighlight> |
||
{{out}}<pre> 81</pre> |
{{out}}<pre> 81</pre> |
||
=={{header|Hare}}== |
=={{header|Hare}}== |
||
< |
<syntaxhighlight lang="hare">use fmt; |
||
use math::random; |
use math::random; |
||
use datetime; |
use datetime; |
||
Line 819: | Line 819: | ||
fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!; |
fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!; |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Creating a custom function: |
Creating a custom function: |
||
< |
<syntaxhighlight lang="haskell">import System.Random (randomRIO) |
||
pick :: [a] -> IO a |
pick :: [a] -> IO a |
||
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1) |
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1) |
||
x <- pick [1, 2, 3]</ |
x <- pick [1, 2, 3]</syntaxhighlight> |
||
Using the random-fu library: |
Using the random-fu library: |
||
< |
<syntaxhighlight lang="haskell">import Data.Random |
||
sample $ randomElement [1, 2, 3]</ |
sample $ randomElement [1, 2, 3]</syntaxhighlight> |
||
For example: |
For example: |
||
< |
<syntaxhighlight lang="haskell">do |
||
x <- sample $ randomElement [1, 2, 3] |
x <- sample $ randomElement [1, 2, 3] |
||
print x</ |
print x</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
The unary operator '?' selects a random element from its argument which may be a string, list, table, or set. |
The unary operator '?' selects a random element from its argument which may be a string, list, table, or set. |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
L := [1,2,3] # a list |
L := [1,2,3] # a list |
||
x := ?L # random element |
x := ?L # random element |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> ({~ ?@#) 'abcdef' |
||
b</ |
b</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.Random; |
||
... |
... |
||
int[] array = {1,2,3}; |
int[] array = {1,2,3}; |
||
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used</ |
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used</syntaxhighlight> |
||
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. |
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}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var array = [1,2,3]; |
||
return array[Math.floor(Math.random() * array.length)];</ |
return array[Math.floor(Math.random() * array.length)];</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 872: | Line 872: | ||
to define one if an external source of entropy is available. In this entry, `/dev/urandom` |
to define one if an external source of entropy is available. In this entry, `/dev/urandom` |
||
is used like so: |
is used like so: |
||
< |
<syntaxhighlight lang="sh">< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq"># Output: a prn in range(0;$n) where $n is `.` |
||
def prn: |
def prn: |
||
if . == 1 then 0 |
if . == 1 then 0 |
||
Line 884: | Line 884: | ||
# An illustration - 10 selections at random with replacement: |
# An illustration - 10 selections at random with replacement: |
||
range(0;10) | ["a", "b", "c"] | .[length|prn]</ |
range(0;10) | ["a", "b", "c"] | .[length|prn]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 891: | Line 891: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">array = [1,2,3] |
||
rand(array)</ |
rand(array)</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> 1?"abcdefg" |
||
,"e"</ |
,"e"</syntaxhighlight> |
||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
< |
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
||
:pickran len rand * 1 + get ; |
:pickran len rand * 1 + get ; |
||
Line 907: | Line 907: | ||
10 [drop pickran ?] for |
10 [drop pickran ?] for |
||
" " input</ |
" " input</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>("nest", "list") |
<pre>("nest", "list") |
||
Line 921: | Line 921: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.2.10 |
||
import java.util.Random |
import java.util.Random |
||
Line 950: | Line 950: | ||
println("\nA randomly selected element from the list is ${list.getRandomElement()}") |
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)}") |
println("\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}") |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 967: | Line 967: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local( |
||
my array = array('one', 'two', 3) |
my array = array('one', 'two', 3) |
||
) |
) |
||
#myarray -> get(integer_random(#myarray -> size, 1))</ |
#myarray -> get(integer_random(#myarray -> size, 1))</syntaxhighlight> |
||
-> two |
-> two |
||
Line 977: | Line 977: | ||
=={{header|Liberty BASIC}}== |
=={{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. |
The natural way to hold an array of text is in a space- or comma-delimited string, although an array could be used. |
||
< |
<syntaxhighlight lang="lb">list$ ="John Paul George Ringo Peter Paul Mary Obama Putin" |
||
wantedTerm =int( 10 *rnd( 1)) |
wantedTerm =int( 10 *rnd( 1)) |
||
print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")</ |
print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")</syntaxhighlight> |
||
Selecting term 5 in the list, which was Peter |
Selecting term 5 in the list, which was Peter |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">put "Apple,Banana,Peach,Apricot,Pear" into fruits |
||
put item (random(the number of items of fruits)) of fruits</ |
put item (random(the number of items of fruits)) of fruits</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
{{works with|UCB Logo}} |
{{works with|UCB Logo}} |
||
<lang |
<syntaxhighlight lang="logo">pick [1 2 3]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">math.randomseed(os.time()) |
||
local a = {1,2,3} |
local a = {1,2,3} |
||
print(a[math.random(1,#a)])</ |
print(a[math.random(1,#a)])</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]: |
||
randomNum := rand(1 ..numelems(a)): |
randomNum := rand(1 ..numelems(a)): |
||
a[randomNum()];</ |
a[randomNum()];</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">RandomChoice[{a, b, c}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>c</pre> |
<pre>c</pre> |
||
Line 1,008: | Line 1,008: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
In case list is a cell array: |
In case list is a cell array: |
||
< |
<syntaxhighlight lang="matlab"> list = {'a','b','c'}; |
||
list{ceil(rand(1)*length(list))}</ |
list{ceil(rand(1)*length(list))}</syntaxhighlight> |
||
If list is a vector: |
If list is a vector: |
||
< |
<syntaxhighlight lang="matlab"> list = 1:1000; |
||
list(ceil(rand(1)*length(list)))</ |
list(ceil(rand(1)*length(list)))</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">random_element(l):= part(l, 1+random(length(l))); |
||
/* (%i1) random_element(['a, 'b, 'c]); |
/* (%i1) random_element(['a, 'b, 'c]); |
||
(%o1) c |
(%o1) c |
||
*/</ |
*/</syntaxhighlight> |
||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>0 П0 1 П1 2 П2 3 П3 4 П4 5 |
<syntaxhighlight lang="text">0 П0 1 П1 2 П2 3 П3 4 П4 5 |
||
^ СЧ * [x] ПE КИПE С/П</ |
^ СЧ * [x] ПE КИПE С/П</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="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} |
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))]</ |
println list[new(Random).getInt(len(list))]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,035: | Line 1,035: | ||
=={{header|NetLogo}}== |
=={{header|NetLogo}}== |
||
< |
<syntaxhighlight lang="netlogo">;; from list containnig only literals and literal constants |
||
user-message one-of [ 1 3 "rooster" blue ] |
user-message one-of [ 1 3 "rooster" blue ] |
||
;; from list containing variables and reporters |
;; from list containing variables and reporters |
||
user-message one-of (list (red + 2) turtles (patch 0 0) )</ |
user-message one-of (list (red + 2) turtles (patch 0 0) )</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols nobinary |
options replace format comments java crossref savelog symbols nobinary |
||
Line 1,054: | Line 1,054: | ||
say v1 v2 v3 |
say v1 v2 v3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
<syntaxhighlight lang="newlisp"> |
|||
<lang NewLISP> |
|||
(define (pick-random-element R) |
(define (pick-random-element R) |
||
(nth (rand (length R)) R)) |
(nth (rand (length R)) R)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: |
Example: |
||
<pre> |
<pre> |
||
Line 1,071: | Line 1,071: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import random |
||
randomize() |
randomize() |
||
let ls = @["foo", "bar", "baz"] |
let ls = @["foo", "bar", "baz"] |
||
echo sample(ls)</ |
echo sample(ls)</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">values := [1, 2, 3]; |
||
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];</ |
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
With a list: |
With a list: |
||
< |
<syntaxhighlight lang="ocaml">let list_rand lst = |
||
let len = List.length lst in |
let len = List.length lst in |
||
List.nth lst (Random.int len)</ |
List.nth lst (Random.int len)</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,093: | Line 1,093: | ||
With an array: |
With an array: |
||
< |
<syntaxhighlight lang="ocaml">let array_rand ary = |
||
let len = Array.length ary in |
let len = Array.length ary in |
||
ary.(Random.int len)</ |
ary.(Random.int len)</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,104: | Line 1,104: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: pickRand(l) l size rand l at ;</syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(import (otus random!)) |
(import (otus random!)) |
||
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday")) |
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday")) |
||
(print (list-ref x (rand! (length x)))) |
(print (list-ref x (rand! (length x)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">pick(v)=v[random(#v)+1]</syntaxhighlight> |
||
=={{header|Pascal}} / {{header|Delphi}} / {{header|Free Pascal}}== |
=={{header|Pascal}} / {{header|Delphi}} / {{header|Free Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program PickRandomElement (output); |
||
const |
const |
||
Line 1,126: | Line 1,126: | ||
randomize; |
randomize; |
||
writeln(s[low(s) + random(length(s))]); |
writeln(s[low(s) + random(length(s))]); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my @array = qw(a b c); |
||
print $array[ rand @array ];</ |
print $array[ rand @array ];</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{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. |
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. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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: #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> |
<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}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">$arr = array('foo', 'bar', 'baz'); |
||
$x = $arr[array_rand($arr)];</ |
$x = $arr[array_rand($arr)];</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
% single element |
% single element |
||
Line 1,163: | Line 1,163: | ||
% Pick a random element from a list L. |
% Pick a random element from a list L. |
||
choice(List) = List[choice(List.length)], list(List) => true.</ |
choice(List) = List[choice(List.length)], list(List) => true.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,172: | Line 1,172: | ||
This is a more structured output. |
This is a more structured output. |
||
{{trans|Ada}} |
{{trans|Ada}} |
||
< |
<syntaxhighlight lang="picat">go2 => |
||
_ = random2(), |
_ = random2(), |
||
Vowels = "aeiou", |
Vowels = "aeiou", |
||
Line 1,182: | Line 1,182: | ||
: _ in 1..3] , |
: _ in 1..3] , |
||
println(RandWords), |
println(RandWords), |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,189: | Line 1,189: | ||
Get the random elements from a frequency table (converted to a "Roulette wheel"). |
Get the random elements from a frequency table (converted to a "Roulette wheel"). |
||
< |
<syntaxhighlight lang="picat">% Pick according to a frequency table |
||
go3 => |
go3 => |
||
_ = random2(), |
_ = random2(), |
||
Line 1,211: | Line 1,211: | ||
Chars := Chars ++ [C : _ in 1..ceiling(10*F)] |
Chars := Chars ++ [C : _ in 1..ceiling(10*F)] |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,226: | Line 1,226: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(get Lst (rand 1 (length Lst)))</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli"> declare t(0:9) character (1) static initial |
||
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); |
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); |
||
put ( t(10*random()) );</ |
put ( t(10*random()) );</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,240: | Line 1,240: | ||
Powershell has Get-Random Cmdlet which one of its overload is to select randomly from a given list |
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 |
1..100 | Get-Random -Count 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
{{works with|SWI-Prolog|6}} |
{{works with|SWI-Prolog|6}} |
||
< |
<syntaxhighlight lang="prolog"> |
||
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]). |
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]). |
||
M = i. |
M = i. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure.s pickRandomElement(List source.s()) |
||
Protected x = ListSize(source()) |
Protected x = ListSize(source()) |
||
Line 1,292: | Line 1,292: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten |
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten |
||
Line 1,298: | Line 1,298: | ||
Random picks from list: Seven Nine Two Six Four Four Nine Three Six Two</pre> |
Random picks from list: Seven Nine Two Six Four Four Nine Three Six Two</pre> |
||
===Easy version=== |
===Easy version=== |
||
< |
<syntaxhighlight lang="purebasic">OpenConsole() |
||
a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+ |
a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+ |
||
Line 1,308: | Line 1,308: | ||
Print(StringField(a$,Random(CountString(a$,#TAB$),1),#TAB$)+#TAB$) |
Print(StringField(a$,Random(CountString(a$,#TAB$),1),#TAB$)+#TAB$) |
||
Next |
Next |
||
Input()</ |
Input()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten |
<pre>Source list: One Two Three Four Five Six Seven Eight Nine Ten |
||
Line 1,314: | Line 1,314: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">>>> import random |
||
>>> random.choice(['foo', 'bar', 'baz']) |
>>> random.choice(['foo', 'bar', 'baz']) |
||
'baz'</ |
'baz'</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ dup size random peek ] is pick ( [ --> x ) |
||
randomise |
randomise |
||
' [ 20 33 -15 7 0 ] pick echo cr |
' [ 20 33 -15 7 0 ] pick echo cr |
||
' pick pick echo</ |
' pick pick echo</syntaxhighlight> <!-- just to make the point that data and code are not differentiated --> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,331: | Line 1,331: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus"># a vector (letters are builtin) |
||
letters |
letters |
||
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" |
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" |
||
Line 1,342: | Line 1,342: | ||
# picking some elements with repetition, and concatenating to get a word |
# picking some elements with repetition, and concatenating to get a word |
||
paste(sample(letters, 10, rep=T), collapse="") |
paste(sample(letters, 10, rep=T), collapse="") |
||
# [1] "episxgcgmt"</ |
# [1] "episxgcgmt"</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
(define (pick-item l) |
(define (pick-item l) |
||
(list-ref l (random (length l)))) |
(list-ref l (random (length l)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 1,357: | Line 1,357: | ||
In a nutshell, picking an element from a list |
In a nutshell, picking an element from a list |
||
is implemented with a method conveniently called "pick": |
is implemented with a method conveniently called "pick": |
||
<lang |
<syntaxhighlight lang="raku" line>say (1, 2, 3).pick;</syntaxhighlight> |
||
There are various ways of doing something similar, though. |
There are various ways of doing something similar, though. |
||
Line 1,365: | Line 1,365: | ||
Selection with replacement: (roll of a die) |
Selection with replacement: (roll of a die) |
||
<lang |
<syntaxhighlight lang="raku" line>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(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</ |
say (1..6).roll(*)[^100]; # return first 100 values from a lazy infinite list of random values in the range 1 through 6</syntaxhighlight> |
||
Selection without replacement: (pick a card from a deck) |
Selection without replacement: (pick a card from a deck) |
||
<lang |
<syntaxhighlight lang="raku" line># define the deck |
||
my @deck = <2 3 4 5 6 7 8 9 J Q K A> X~ <♠ ♣ ♥ ♦>; |
my @deck = <2 3 4 5 6 7 8 9 J Q K A> X~ <♠ ♣ ♥ ♦>; |
||
say @deck.pick; # Pick a card |
say @deck.pick; # Pick a card |
||
say @deck.pick(5); # Draw 5 |
say @deck.pick(5); # Draw 5 |
||
say @deck.pick(*); # Get a shuffled deck</ |
say @deck.pick(*); # Get a shuffled deck</syntaxhighlight> |
||
Or you can always use the normal <tt>rand</tt> built-in |
Or you can always use the normal <tt>rand</tt> built-in |
||
to generate a subscript (which automatically truncates any fractional part): |
to generate a subscript (which automatically truncates any fractional part): |
||
<lang |
<syntaxhighlight lang="raku" line>@array[@array * rand]</syntaxhighlight> |
||
However, the <tt>pick</tt> and <tt>roll</tt> methods (not to be confused |
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 |
with the pick-and-roll method in basketball) are more general |
||
insofar as they may be used on any enumerable type: |
insofar as they may be used on any enumerable type: |
||
<lang |
<syntaxhighlight lang="raku" line>say Bool.pick; # returns either True or False</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">>> random/only collect [repeat i 10 [keep i]]</syntaxhighlight> |
||
=={{header|ReScript}}== |
=={{header|ReScript}}== |
||
< |
<syntaxhighlight lang="rescript">let fruits = ["apple", "banana", "coconut", "orange", "lychee"] |
||
let pickRand = arr => { |
let pickRand = arr => { |
||
Line 1,395: | Line 1,395: | ||
} |
} |
||
Js.log(pickRand(fruits))</ |
Js.log(pickRand(fruits))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ bsc pickrand.res > pickrand.bs.js |
<pre>$ bsc pickrand.res > pickrand.bs.js |
||
Line 1,407: | Line 1,407: | ||
Also, the newly named elements have been incorporated into this table. |
Also, the newly named elements have been incorporated into this table. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/ |
||
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium' |
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium' |
||
_=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium' |
_=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium' |
||
Line 1,427: | Line 1,427: | ||
#= words(_) /*obtain the number of words in list. */ |
#= words(_) /*obtain the number of words in list. */ |
||
item= word(_, random(1, #) ) /*pick a random word (element) in list.*/ |
item= word(_, random(1, #) ) /*pick a random word (element) in list.*/ |
||
say 'random element: ' item /*stick a fork in it, we're all done. */</ |
say 'random element: ' item /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output}} |
{{out|output}} |
||
<pre> |
<pre> |
||
Line 1,438: | Line 1,438: | ||
<br>smaller limit of the total length of a clause, in particular PC/REXX and Personal REXX |
<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). |
<br>which have a limit of 1,000 characters). |
||
< |
<syntaxhighlight lang="rexx"> |
||
/* REXX *************************************************************** |
/* REXX *************************************************************** |
||
* 18.10.2012 Walter Pachl Not only the list of elements shortened:-) |
* 18.10.2012 Walter Pachl Not only the list of elements shortened:-) |
||
Line 1,448: | Line 1,448: | ||
Say word(wl,random(1,words(wl))) |
Say word(wl,random(1,words(wl))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
aList = "abcdefghij" |
aList = "abcdefghij" |
||
for i = 1 to 10 |
for i = 1 to 10 |
||
Line 1,459: | Line 1,459: | ||
ok |
ok |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby"> |
||
%w(north east south west).sample # => "west" |
%w(north east south west).sample # => "west" |
||
(1..100).to_a.sample(2) # => [17, 79]</ |
(1..100).to_a.sample(2) # => [17, 79]</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">list$ = "a,b,c,d,e,f,g,h,i,j" |
||
letter = rnd(1) * 10 |
letter = rnd(1) * 10 |
||
print "Selected letter:"; word$(list$,letter,",")</ |
print "Selected letter:"; word$(list$,letter,",")</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{libheader|rand}} |
{{libheader|rand}} |
||
< |
<syntaxhighlight lang="rust">extern crate rand; |
||
use rand::Rng; |
use rand::Rng; |
||
Line 1,482: | Line 1,482: | ||
println!("{}", rng.choose(&array).unwrap()); |
println!("{}", rng.choose(&array).unwrap()); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{libheader|Scala}} |
{{libheader|Scala}} |
||
< |
<syntaxhighlight lang="scala">val a = (1 to 10).toList |
||
println(scala.util.Random.shuffle(a).head)</ |
println(scala.util.Random.shuffle(a).head)</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
begin |
begin |
||
writeln(rand([] ("foo", "bar", "baz"))); |
writeln(rand([] ("foo", "bar", "baz"))); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var arr = %w(north east south west); |
||
say arr.rand; |
say arr.rand; |
||
say arr.rand(2).dump;</ |
say arr.rand(2).dump;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>south |
<pre>south |
||
Line 1,507: | Line 1,507: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">x := #(1 2 3) atRandom.</syntaxhighlight> |
||
=={{header|SuperCollider}}== |
=={{header|SuperCollider}}== |
||
<lang |
<syntaxhighlight lang="supercollider">[1, 2, 3].choose</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">import Darwin |
||
let myList = [1, 2, 4, 5, 62, 234, 1, -1] |
let myList = [1, 2, 4, 5, 62, 234, 1, -1] |
||
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])</ |
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 1,522: | Line 1,522: | ||
(for selection of an item from a list) and the pattern for generating an integral random number from the range <math>[0,n)</math>. |
(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: |
It's simpler to use when wrapped up as a helper procedure: |
||
< |
<syntaxhighlight lang="tcl">proc randelem {list} { |
||
lindex $list [expr {int(rand()*[llength $list])}] |
lindex $list [expr {int(rand()*[llength $list])}] |
||
} |
} |
||
set x [randelem {1 2 3 4 5}]</ |
set x [randelem {1 2 3 4 5}]</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT |
||
list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin" |
list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin" |
||
sizeList=SIZE(list) |
sizeList=SIZE(list) |
||
selectedNr=RANDOM_NUMBERS (1,sizeList,1) |
selectedNr=RANDOM_NUMBERS (1,sizeList,1) |
||
selectedItem=SELECT(list,#selectednr) |
selectedItem=SELECT(list,#selectednr) |
||
PRINT "Selecting term ",selectedNr," in the list, which was ",selectedItem</ |
PRINT "Selecting term ",selectedNr," in the list, which was ",selectedItem</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,542: | Line 1,542: | ||
{{trans|Tcl}} |
{{trans|Tcl}} |
||
< |
<syntaxhighlight lang="txr">@(do (defun randelem (seq) |
||
[seq (random nil (length seq))])) |
[seq (random nil (length seq))])) |
||
@(bind x @(randelem #("a" "b" "c" "d")))</ |
@(bind x @(randelem #("a" "b" "c" "d")))</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bourne Again Shell}} |
{{works with|Bourne Again Shell}} |
||
< |
<syntaxhighlight lang="sh">list=(these are some words) |
||
printf '%s\n' "${list[RANDOM%${#list[@]}]}"</ |
printf '%s\n' "${list[RANDOM%${#list[@]}]}"</syntaxhighlight> |
||
{{works with|Zsh}} |
{{works with|Zsh}} |
||
< |
<syntaxhighlight lang="sh">list=(these are some words) |
||
printf '%s\n' "$list[RANDOM%$#list+1]"</ |
printf '%s\n' "$list[RANDOM%$#list+1]"</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># generate a stream (ursa equivalent of a list) |
||
decl string<> str |
decl string<> str |
||
append "these" "are" "some" "values" str |
append "these" "are" "some" "values" str |
||
decl ursa.util.random r |
decl ursa.util.random r |
||
out str<(r.getint (size str))> endl console</ |
out str<(r.getint (size str))> endl console</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Option Explicit |
Option Explicit |
||
Line 1,577: | Line 1,577: | ||
Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray)))) |
Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray)))) |
||
End Function |
End Function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Function pick_random(arr) |
||
Set objRandom = CreateObject("System.Random") |
Set objRandom = CreateObject("System.Random") |
||
pick_random = arr(objRandom.Next_2(0,UBound(arr)+1)) |
pick_random = arr(objRandom.Next_2(0,UBound(arr)+1)) |
||
End Function |
End Function |
||
WScript.Echo pick_random(Array("a","b","c","d","e","f"))</ |
WScript.Echo pick_random(Array("a","b","c","d","e","f"))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,592: | Line 1,592: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Module Program |
||
Sub Main() |
Sub Main() |
||
Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) |
Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) |
||
Line 1,599: | Line 1,599: | ||
Console.WriteLine("I picked element {0}", randomElement) |
Console.WriteLine("I picked element {0}", randomElement) |
||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">import rand |
||
fn main() { |
fn main() { |
||
list := ["friends", "peace", "people", "happiness", "hello", "world"] |
list := ["friends", "peace", "people", "happiness", "hello", "world"] |
||
for index in 1..list.len + 1 {println(index.str() + ': ' + list[rand.intn(list.len) or {}])} |
for index in 1..list.len + 1 {println(index.str() + ': ' + list[rand.intn(list.len) or {}])} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,621: | Line 1,621: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">import "random" for Random |
||
var rand = Random.new() |
var rand = Random.new() |
||
var colors = ["red", "green", "blue", "yellow", "pink"] |
var colors = ["red", "green", "blue", "yellow", "pink"] |
||
for (i in 0..4) System.print(colors[rand.int(colors.count)])</ |
for (i in 0..4) System.print(colors[rand.int(colors.count)])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,638: | Line 1,638: | ||
=={{header|XBS}}== |
=={{header|XBS}}== |
||
< |
<syntaxhighlight lang="xbs">set Array = ["Hello","World",1,2,3]; |
||
log(Array[rnd(0,?Array-1)]);</ |
log(Array[rnd(0,?Array-1)]);</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code Ran=1, Text=12; |
||
int List; |
int List; |
||
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX) |
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX) |
||
Text(0, List(Ran(5))); |
Text(0, List(Ran(5))); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Zig}}== |
=={{header|Zig}}== |
||
This example uses the [http://www.pcg-random.org/ PCG] algorithm. |
This example uses the [http://www.pcg-random.org/ PCG] algorithm. |
||
< |
<syntaxhighlight lang="zig">const std = @import("std"); |
||
const debug = std.debug; |
const debug = std.debug; |
||
Line 1,680: | Line 1,680: | ||
debug.warn("\n", .{}); |
debug.warn("\n", .{}); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,696: | Line 1,696: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|XPL0}} |
{{trans|XPL0}} |
||
< |
<syntaxhighlight lang="zkl">list:=T("hydrogen", "helium", "lithium", "beryllium", "boron"); |
||
list[(0).random(list.len())]</ |
list[(0).random(list.len())]</syntaxhighlight> |
Revision as of 01:39, 28 August 2022
![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.
11l
print(random:choice([‘foo’, ‘bar’, ‘baz’]))
8086 Assembly
The easiest way to pick a random element from a list is to use a random number generator's output as an index into an array. Care must be taken not to index out of bounds. If the array's size is a power of 2, then index = RNG output & (array size - 1)
will ensure that the array is not indexed out of bounds while maintaining the randomness of the selection. Otherwise, you will have to manually check the RNG output against the array's size and roll again if the RNG output is larger.
For brevity's sake, the implementations of the RNG and printing routines were left out; they can be provided if requested.
.model small
.stack 1024
.data
TestList byte 00h,05h,10h,15h,20h,25h,30h,35h
.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
call seedXorshift32 ;seeds the xorshift rng using the computer's date and time
call doXorshift32
mov ax,word ptr [ds:xorshift32_state_lo] ;retrieve the rng output
and al,00000111b ;constrain the rng to values 0-7
mov bx,offset TestList
XLAT ;translate AL according to [DS:BX]
call PrintHex ;display AL to the terminal
mov ax,4C00h
int 21h ;exit program and return to MS-DOS
end start
- Output:
(After four runs of the program)
05 20 15 30
ACL2
:set-state-ok t
(defun pick-random-element (xs state)
(mv-let (idx state)
(random$ (len xs) state)
(mv (nth idx xs) state)))
Action!
PROC Main()
DEFINE PTR="CARD"
PTR ARRAY a(7)
BYTE i,index
a(0)="Monday"
a(1)="Tuesday"
a(2)="Wednesday"
a(3)="Thursday"
a(4)="Friday"
a(5)="Saturday"
a(6)="Sunday"
FOR i=1 TO 20
DO
index=Rand(7)
PrintE(a(index))
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
Thursday Tuesday Friday Friday Saturday Tuesday Monday Saturday Sunday Wednesday Monday Friday Wednesday Saturday Friday Thursday Saturday Saturday Wednesday Wednesday
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.
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
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[drand(5)]);
o_byte('\n');
ALGOL 68
# 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
APL
pickRandom ← (?≢)⊃⊢
- Output:
pickRandom 'ABCDE' E pickRandom 'ABCDE' D pickRandom 'ABCDE' A
App Inventor
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
AppleScript
get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday]
- Output:
"two"
Arturo
fruit: ["apple" "banana" "pineapple" "apricot" "watermelon"]
print sample fruit
- Output:
pineapple
AutoHotkey
- True Arrays
list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint]
- Pseudo-Arrays
list := "abc,def,gh,ijklmnop,hello,world"
StringSplit list, list, `,
Random, randint, 1, %list0%
MsgBox % List%randint%
AWK
# 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
BaCon
This is simply an application of a ranged random number used as an array index. BaCon has no built in random element selector.
' Pick random element
OPTION BASE 1
DECLARE words$[6]
FOR i = 1 TO 6 : READ words$[i] : NEXT
DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"
element = RANDOM(6) + 1
PRINT "Chose ", element, ": ", words$[element]
- Output:
prompt$ ./pick-random-element Chose 2: Beta prompt$ ./pick-random-element Chose 1: Alpha prompt$ ./pick-random-element Chose 5: Epsilon
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"
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)
.)
'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
Applesoft BASIC
This is the same as the 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.
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
Commodore BASIC
10 DIM A$(9)
20 FOR I=0 TO 9 : READ A$(I) : NEXT
30 X = RND(-TI) : REM 'PLANT A RANDOM SEED'
40 X = INT(RND(1)*10)
50 PRINT A$(X)
60 END
100 DATA ALPHA, BRAVO, CHARLIE, DELTA, ECHO
110 DATA FOXTROT, GOLF, HOTEL, INDIA, JULIETT
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
True BASIC
!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
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
Batch File
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
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'
BQN
PR1
is a tacit translation of PR
.
Both use BQN's system value •rand
, which contains multiple functions for generating random values.
PR ← {𝕩⊑˜•rand.Range ≠𝕩}
PR1 ← •rand.Range∘≠⊸⊑
- Usage:
PR 5‿67‿7‿23
67
PR1 5‿67‿7‿23
7
Burlesque
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
int i;
time_t t;
srand((unsigned)time(&t));
for(i=0;i<30;i++){
printf("%c\n", array[rand()%10]);
}
return 0;
}
Output
a e f h b d g a b f a i b d d g j a f e a e g e i d j a f e a
C#
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);
}
}
C++
#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 ;
}
Ceylon
import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
value element = random.nextElement([1, 2, 3, 4, 5, 6]);
print(element);
}
Clojure
(rand-nth coll)
where coll
is some sequential collection. Equivalent to:
(nth coll (rand-int (count coll)))
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
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
arr: array[string] := array[string]$["foo", "bar", "baz", "qux"]
for i: int in int$from_to(1,5) do
stream$putl(po, random_element[string](arr))
end
end start_up
- Output:
qux foo qux bar foo
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
array = [1,2,3]
console.log array[Math.floor(Math.random() * array.length)]
Common 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*))
- Output:
FIVE THREE ONE
Crystal
puts [1, 2, 3, 4, 5].sample(1)
D
import std.stdio, std.random;
void main() {
const items = ["foo", "bar", "baz"];
items[uniform(0, $)].writeln;
}
Delphi
See #Pascal / Delphi / Free Pascal.
Déjà Vu
!print choose [ "one" "two" "chicken" ]
EasyLang
ar$[] = [ "spring" "summer" "autumn" "winter" ]
print ar$[random len ar$[]]
EchoLisp
(define (pick-random list)
(list-ref list (random (length list))))
(pick-random (iota 1000)) → 667
(pick-random (iota 1000)) → 179
Elena
ELENA 5.0 :
import extensions;
extension listOp
{
randomItem()
= self[randomGenerator.eval(self.Length)];
}
public program()
{
var item := new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
console.printLine("I picked element ",item.randomItem())
}
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]
Emacs Lisp
(defun random-choice (items)
(nth (random (length items)) items))
(random-choice '("a" "b" "c"))
;; => "a"
Erlang
% Implemented by Arjun Sunel
-module(pick_random).
-export([main/0]).
main() ->
List =[1,2,3,4,5],
Index = rand:uniform(length(List)),
lists:nth(Index,List).
Euphoria
constant s = {'a', 'b', 'c'}
puts(1,s[rand($)])
F#
let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)]
Factor
( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a"
Falcon
lst = [1, 3, 5, 8, 10]
> randomPick(lst)
Fortran
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
See #Pascal / Delphi / Free Pascal.
FreeBASIC
' FB 1.05.0 Win64
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Randomize
Dim randInt As Integer
For i As Integer = 1 To 5
randInt = Int(Rnd * 10)
Print a(randInt)
Next
Sleep
Sample output :
- Output:
Zero Seven Three Nine Three
Frink
a = ["one", "two", "three"]
println[random[a]]
Gambas
You can run this code. Copy the code, click this link, paste it in and press 'Run !'
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
Output:
May
GAP
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
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
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]
GW-BASIC
10 RANDOMIZE TIMER : REM set random number seed to something arbitrary
20 DIM ARR(10) : REM initialise array
30 FOR I = 1 TO 10
40 ARR(I) = I*I : REM squares of the integers is OK as a demo
50 NEXT I
60 C = 1 + INT(RND*10) : REM get a random index from 1 to 10 inclusive
70 PRINT ARR(C)
- Output:
81
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)])!;
};
Haskell
Creating a custom function:
import System.Random (randomRIO)
pick :: [a] -> IO a
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)
x <- pick [1, 2, 3]
Using the random-fu library:
import Data.Random
sample $ randomElement [1, 2, 3]
For example:
do
x <- sample $ randomElement [1, 2, 3]
print x
Icon and Unicon
The unary operator '?' selects a random element from its argument which may be a string, list, table, or set.
J
({~ ?@#) 'abcdef'
b
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
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
var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];
jq
Works with gojq, the Go implementation of jq
Neither jq nor gojq currently has a built-in PRNG, but it is quite straightforward to define one if an external source of entropy is available. In this entry, `/dev/urandom` is used like so:
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
# Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
else . as $n
| ([1, (($n-1)|tostring|length)]|max) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
# An illustration - 10 selections at random with replacement:
range(0;10) | ["a", "b", "c"] | .[length|prn]
- Output:
bcbabacbbc
Julia
array = [1,2,3]
rand(array)
K
1?"abcdefg"
,"e"
Klingphix
include ..\Utilitys.tlhy
:pickran len rand * 1 + get ;
( 1 3.1415 "Hello world" ( "nest" "list" ) )
10 [drop pickran ?] for
" " input
- Output:
("nest", "list") 3.1415 ("nest", "list") Hello world 1 Hello world 3.1415 ("nest", "list") 1 3.1415
Kotlin
// version 1.2.10
import java.util.Random
/**
* Extension function on any list that will return a random element from index 0
* to the last index
*/
fun <E> List<E>.getRandomElement() = this[Random().nextInt(this.size)]
/**
* Extension function on any list that will return a list of unique random picks
* from the list. If the specified number of elements you want is larger than the
* number of elements in the list it returns null
*/
fun <E> List<E>.getRandomElements(numberOfElements: Int): List<E>? {
if (numberOfElements > this.size) {
return null
}
return this.shuffled().take(numberOfElements)
}
fun main(args: Array<String>) {
val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2)
println("The list consists of the following numbers:\n${list}")
// notice we can call our extension functions as if they were regular member functions of List
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)}")
}
Sample output:
- Output:
The list consists of the following numbers: [1, 16, 3, 7, 17, 24, 34, 23, 11, 2] A randomly selected element from the list is 11 A random sequence of 5 elements from the list is [17, 24, 23, 16, 3]
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.
Lasso
local(
my array = array('one', 'two', 3)
)
#myarray -> get(integer_random(#myarray -> size, 1))
-> two
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.
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
put "Apple,Banana,Peach,Apricot,Pear" into fruits
put item (random(the number of items of fruits)) of fruits
Logo
pick [1 2 3]
Lua
math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)])
Maple
a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]:
randomNum := rand(1 ..numelems(a)):
a[randomNum()];
Mathematica /Wolfram Language
RandomChoice[{a, b, c}]
- Output:
c
MATLAB / Octave
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
random_element(l):= part(l, 1+random(length(l)));
/* (%i1) random_element(['a, 'b, 'c]);
(%o1) c
*/
МК-61/52
0 П0 1 П1 2 П2 3 П3 4 П4 5
^ СЧ * [x] ПE КИПE С/П
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))]
- Output:
12
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) )
NetRexx
/* 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
(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
import random
randomize()
let ls = @["foo", "bar", "baz"]
echo sample(ls)
Objeck
values := [1, 2, 3];
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];
OCaml
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
: pickRand(l) l size rand l at ;
Ol
(import (otus random!))
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))
PARI/GP
pick(v)=v[random(#v)+1]
Pascal / Delphi / Free 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.
Perl
my @array = qw(a b c);
print $array[ rand @array ];
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.
with javascript_semantics constant s = {1,2.5,"three",{4,{"4 as well"}}} pp(s[rand(length(s))])
PHP
$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
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.
- Output:
choice = 4 [7,8,6,4,6,7,3,10,2,3] ekcealmnei
This is a more structured output.
go2 =>
_ = random2(),
Vowels = "aeiou",
Consonants = "tnshrdl",
Specials = ",.?!",
RandWords = [( [[Consonants.choice()] ++ [Vowels.choice()] : _ in 1..10]
++ [Specials.choice()]
).flatten()
: _ in 1..3] ,
println(RandWords),
nl.
- Output:
[dodidosisahuhiretesi,,loledohusoluhusululu?,tunuridunoheditonudu!]
Get the random elements from a frequency table (converted to a "Roulette wheel").
% 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.
- Output:
ihvuotpswieecanrv gnelhlutnopytoss aentkttnenb cnyawephc nsioetohasedd yapaeofyt setmtoorwloiar nsssrkcfgnpadtifln rrlwree nawmtnie
PicoLisp
(get Lst (rand 1 (length Lst)))
PL/I
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
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
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).
M = i.
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
- 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
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
>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Quackery
[ dup size random peek ] is pick ( [ --> x )
randomise
' [ 20 33 -15 7 0 ] pick echo cr
' pick pick echo
- Output:
33 random
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"
Racket
#lang racket
(define (pick-item l)
(list-ref l (random (length l))))
Raku
(formerly Perl 6)
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. Raku 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)
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
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~ <♠ ♣ ♥ ♦>;
say @deck.pick; # Pick a card
say @deck.pick(5); # Draw 5
say @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
Red
>> random/only collect [repeat i 10 [keep i]]
ReScript
let fruits = ["apple", "banana", "coconut", "orange", "lychee"]
let pickRand = arr => {
let len = Js.Array.length(arr)
let i = Js.Math.random_int(0, len)
arr[i]
}
Js.log(pickRand(fruits))
- Output:
$ bsc pickrand.res > pickrand.bs.js $ node pickrand.bs.js lychee
REXX
version 1
This REXX example takes the Rosetta Code task very literally.
Also, the newly named elements have been incorporated into this table.
/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/
_= '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 iridium platinum'
_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium radium actinium'
_=_ 'thorium protactinium uranium neptunium plutonium americium curium berkelium'
_=_ 'californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium'
_=_ 'seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium'
_=_ 'flerovium moscovium livermorium tennessine oganesson ununenniym unbinvlium umbiunium'
/*───── You can't trust atoms, ─────*/
/*───── they make everything up. ─────*/
#= words(_) /*obtain the number of words in list. */
item= word(_, random(1, #) ) /*pick a random word (element) in list.*/
say 'random element: ' item /*stick a fork in it, we're all done. */
- output:
random element: tennessine
version 2
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
aList = "abcdefghij"
for i = 1 to 10
letter = random(9) + 1
if letter > 0
see aList[letter] + nl
ok
next
Ruby
%w(north east south west).sample # => "west"
(1..100).to_a.sample(2) # => [17, 79]
Run BASIC
list$ = "a,b,c,d,e,f,g,h,i,j"
letter = rnd(1) * 10
print "Selected letter:"; word$(list$,letter,",")
Rust
extern crate rand;
use rand::Rng;
fn main() {
let array = [5,1,2,5,6,7,8,1,2,4,5];
let mut rng = rand::thread_rng();
println!("{}", rng.choose(&array).unwrap());
}
Scala
val a = (1 to 10).toList
println(scala.util.Random.shuffle(a).head)
Seed7
$ include "seed7_05.s7i";
const proc: main is func
begin
writeln(rand([] ("foo", "bar", "baz")));
end func;
Sidef
var arr = %w(north east south west);
say arr.rand;
say arr.rand(2).dump;
- Output:
south ['west', 'south']
Smalltalk
x := #(1 2 3) atRandom.
SuperCollider
[1, 2, 3].choose
Swift
import Darwin
let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])
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:
proc randelem {list} {
lindex $list [expr {int(rand()*[llength $list])}]
}
set x [randelem {1 2 3 4 5}]
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
- Output:
Selecting term 3 in the list, which was George
TXR
@(do (defun randelem (seq)
[seq (random nil (length seq))]))
@(bind x @(randelem #("a" "b" "c" "d")))
UNIX Shell
list=(these are some words)
printf '%s\n' "${list[RANDOM%${#list[@]}]}"
list=(these are some words)
printf '%s\n' "$list[RANDOM%$#list+1]"
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
VBA
Option Explicit
Sub Main_Pick_Random_Element()
Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub
Function Pick_Random_Element(myArray)
Randomize Timer
Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
VBScript
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
Visual Basic .NET
Module Program
Sub Main()
Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
Dim rng As New Random()
Dim randomElement = list(rng.Next(list.Count)) ' Upper bound is exclusive.
Console.WriteLine("I picked element {0}", randomElement)
End Sub
End Module
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 {}])}
}
- Output:
Sample of random output:
1: peace 2: happiness 3: hello 4: friends 5: peace 6: people
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)])
- Output:
Sample run:
blue red pink yellow red
XBS
set Array = ["Hello","World",1,2,3];
log(Array[rnd(0,?Array-1)]);
XPL0
code Ran=1, Text=12;
int List;
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX)
Text(0, List(Ran(5)));
]
Zig
This example uses the PCG algorithm.
const std = @import("std");
const debug = std.debug;
const rand = std.rand;
const time = std.time;
test "pick random element" {
var pcg = rand.Pcg.init(time.milliTimestamp());
const chars = [_]u8{
'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X',
'Y', 'Z', '?', '!',
'<', '>', '(', ')',
};
var i: usize = 0;
while (i < 32) : (i += 1) {
if (i % 4 == 0) {
debug.warn("\n ", .{});
}
debug.warn("'{c}', ", .{chars[pcg.random.int(usize) % chars.len]});
}
debug.warn("\n", .{});
}
- Output:
Test [1/1] test "pick random element"... 'N', 'Q', 'H', '?', 'D', '>', 'Q', 'G', 'U', 'H', 'W', 'U', 'N', '(', 'E', 'K', 'Y', 'V', 'W', 'S', 'U', 'V', 'H', '<', 'Z', 'O', 'C', 'D', 'Y', 'J', '?', 'L', All 1 tests passed.
zkl
list:=T("hydrogen", "helium", "lithium", "beryllium", "boron");
list[(0).random(list.len())]
- Programming Tasks
- Basic language learning
- Randomness
- 11l
- 8086 Assembly
- ACL2
- Action!
- Ada
- Aime
- ALGOL 68
- APL
- App Inventor
- AppleScript
- Arturo
- AutoHotkey
- AWK
- BaCon
- Bash
- BASIC
- Applesoft BASIC
- Commodore BASIC
- BASIC256
- True BASIC
- Yabasic
- Batch File
- BBC BASIC
- BQN
- Burlesque
- C
- C sharp
- C++
- Ceylon
- Clojure
- CLU
- COBOL
- CoffeeScript
- Common Lisp
- Crystal
- D
- Delphi
- Déjà Vu
- EasyLang
- EchoLisp
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- Falcon
- Fortran
- Free Pascal
- FreeBASIC
- Frink
- Gambas
- GAP
- Go
- Groovy
- GW-BASIC
- Hare
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- K
- Klingphix
- Kotlin
- LabVIEW
- Lasso
- Liberty BASIC
- LiveCode
- Logo
- Lua
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- МК-61/52
- Nanoquery
- NetLogo
- NetRexx
- NewLISP
- Nim
- Objeck
- OCaml
- Oforth
- Ol
- PARI/GP
- Pascal
- Perl
- Phix
- PHP
- Picat
- PicoLisp
- PL/I
- Powershell
- Prolog
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- Red
- ReScript
- REXX
- Ring
- Ruby
- Run BASIC
- Rust
- Rand
- Scala
- Seed7
- Sidef
- Smalltalk
- SuperCollider
- Swift
- Tcl
- TUSCRIPT
- TXR
- UNIX Shell
- Ursa
- VBA
- VBScript
- Visual Basic .NET
- Vlang
- Wren
- XBS
- XPL0
- Zig
- Zkl
- Pages with too many expensive parser function calls