Pick random element: Difference between revisions
(add Java) |
m (→{{header|Java}}: Added strategy if destroying the list is allowed) |
||
Line 28: | Line 28: | ||
return array[new Random().nextInt(array.length)];</lang> |
return array[new Random().nextInt(array.length)];</lang> |
||
For a List object rather than an array, substitute <code>list.get(...)</code> for <code>array[...]</code>. |
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}}== |
Revision as of 18:20, 9 August 2011
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>
Java
<lang java>import java.util.Random; ... int[] array = {1,2,3}; return array[new Random().nextInt(array.length)];</lang>
For a List object rather than an array, substitute list.get(...)
for array[...]
. If preserving the order of the List isn't important, you could call Collections.shuffle(list);
and then list.get(0);
. You would need to shuffle each time unless you remove
d the item from the list.
JavaScript
<lang javascript>var array = [1,2,3]; return array[Math.floor(Math.random() * array.length)];</lang>
PicoLisp
<lang PicoLisp>(get Lst (rand 1 (length Lst)))</lang>
Ruby
<lang ruby>irb(main):001:0> %w(north east south west).sample => "west" irb(main):002:0> (1..100).to_a.sample(2) => [17, 79]</lang>
<lang ruby>irb(main):001:0> %w(north east south west).choice => "south"</lang>
Smalltalk
<lang smalltalk>x := #(1 2 3) atRandom.</lang>