Pick random element: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎Tcl: Added implementation)
(Tidy up)
Line 1: Line 1:
{{draft task|Basic language learning}}
{{draft task|Basic language learning}}

How does one pick a random element from a list?
How does one pick a random element from a list?


Line 30: Line 29:


=={{header|Java}}==
=={{header|Java}}==

<lang java>import java.util.Random;
<lang java>import java.util.Random;
...
...
Line 39: Line 37:


=={{header|JavaScript}}==
=={{header|JavaScript}}==

<lang javascript>var array = [1,2,3];
<lang javascript>var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];</lang>
return array[Math.floor(Math.random() * array.length)];</lang>
Line 51: Line 48:
</lang>
</lang>
Selecting term 5 in the list, which was Peter
Selecting term 5 in the list, which was Peter



=={{header|OCaml}}==
=={{header|OCaml}}==

<lang ocaml>let list_rand lst =
<lang ocaml>let list_rand lst =
let len = List.length lst in
let len = List.length lst in
Line 67: Line 61:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>pick(v)=v[random(#v)+1]</lang>
<lang parigp>pick(v)=v[random(#v)+1]</lang>



=={{header|PHP}}==
=={{header|PHP}}==
Line 80: Line 73:
(1..6).roll(3); # return a list of 3 random values in the range 1 through 6
(1..6).roll(3); # return a list of 3 random values in the range 1 through 6
(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6</lang>
(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6</lang>



Selection without replacement: (pick a card from a deck)
Selection without replacement: (pick a card from a deck)
Line 101: Line 93:
irb(main):002:0> (1..100).to_a.sample(2)
irb(main):002:0> (1..100).to_a.sample(2)
=> [17, 79]</lang>
=> [17, 79]</lang>

{{works with|Ruby|1.8, but not 1.9}}
{{works with|Ruby|1.8, but not 1.9}}
<lang ruby>irb(main):001:0> %w(north east south west).choice
<lang ruby>irb(main):001:0> %w(north east south west).choice
Line 110: Line 101:


=={{header|Tcl}}==
=={{header|Tcl}}==
Random selection from a list is implemented by composing <code>lindex</code> (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:
<lang tcl>proc randelem {list} {lindex $list [expr {int(rand()*[llength $list])}]}
<lang tcl>proc randelem {list} {
lindex $list [expr {int(rand()*[llength $list])}]
}
set x [randelem {1 2 3 4 5}]</lang>
set x [randelem {1 2 3 4 5}]</lang>

Revision as of 10:13, 11 August 2011

Pick random element is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

How does one pick a random element from a list?

Haskell

Creating a custom function:

<lang haskell>import Random (randomRIO)

pick :: [a] -> IO a pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)

x <- pick [1 2 3]</lang>

Using the random-extras library:

<lang haskell>import Data.Random import Data.Random.Source.DevRandom import Data.Random.Extras

x <- runRVar (choice [1 2 3]) DevRandom</lang>

Icon and Unicon

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

<lang Icon>procedure main()

  L := [1,2,3]  # a list
  x := ?L       # random element

end</lang>

Java

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

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

JavaScript

<lang javascript>var array = [1,2,3]; return array[Math.floor(Math.random() * array.length)];</lang>

Liberty BASIC

The natural way to hold an array of text is in a space- or comma-delimited string, although an array could be used. <lang lb> list$ ="John Paul George Ringo Peter Paul Mary Obama Putin" wantedTerm =int( 10 *rnd( 1)) print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ") </lang>

Selecting term 5 in the list, which was Peter

OCaml

<lang ocaml>let list_rand lst =

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

PARI/GP

<lang parigp>pick(v)=v[random(#v)+1]</lang>

PHP

<lang php>$arr = array('foo', 'bar', 'baz'); $x = $arr[array_rand($arr)];</lang>

Perl 6

Perl 6 has two functions to return random elements depending on whether you are doing selection with or without replacement.

Selection with replacement: (roll of a die) <lang perl6>(1..6).roll; # return 1 random value in the range 1 through 6 (1..6).roll(3); # return a list of 3 random values in the range 1 through 6 (1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6</lang>

Selection without replacement: (pick a card from a deck) <lang perl6>( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick; # Pick a card ( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick(5); # Draw 5 ( 2..9, <J Q K A> X~ <♠ ♣ ♥ ♦> ).pick(*); # Get a shuffled deck</lang>

PicoLisp

<lang PicoLisp>(get Lst (rand 1 (length Lst)))</lang>

Python

<lang python>>>> import random >>> random.choice(['foo', 'bar', 'baz']) 'baz'</lang>

Ruby

Works with: Ruby version 1.9

<lang ruby>irb(main):001:0> %w(north east south west).sample => "west" irb(main):002:0> (1..100).to_a.sample(2) => [17, 79]</lang>

Works with: Ruby version 1.8, but not 1.9

<lang ruby>irb(main):001:0> %w(north east south west).choice => "south"</lang>

Smalltalk

<lang smalltalk>x := #(1 2 3) atRandom.</lang>

Tcl

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

   lindex $list [expr {int(rand()*[llength $list])}]

} set x [randelem {1 2 3 4 5}]</lang>