Pick random element: Difference between revisions
Content deleted Content added
No edit summary |
Add Ruby. |
||
Line 20: | Line 20: | ||
x <- runRVar (choice [1 2 3]) DevRandom</lang> |
x <- runRVar (choice [1 2 3]) DevRandom</lang> |
||
=={{header|Ruby}}== |
|||
{{works with|Ruby|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|1.8, but not 1.9}} |
|||
<lang ruby>irb(main):001:0> %w(north east south west).choice |
|||
=> "south"</lang> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
Revision as of 16:22, 9 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>
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>