Logo

Programming-Idioms

History of Idiom 11 > diff from v20 to v21

Edit summary for version 21 by :

Version 20

2015-09-06, 14:30:32

Version 21

2015-10-29, 14:05:12

Idiom #11 Pick a random element from a list

List x must be non-empty.

Idiom #11 Pick a random element from a list

List x must be non-empty.

Code
return.(x!!)=<<System.Random.randomRIO(0,length x-1)
Code
return.(x!!)=<<System.Random.randomRIO(0,length x-1)
Imports
classes
Imports
classes
Code
element := x.Items[random(x.count)];
Code
element := x.Items[random(x.count)];
Comments bubble
If x is a TList or TStrings -descendent
Comments bubble
If x is a TList or TStrings -descendent
Code
element := x[random(length(x))];
Code
element := x[random(length(x))];
Comments bubble
if x is an Array
Comments bubble
if x is an Array
Code
my @list = ('a', 'list', 'of', 'random', 'item's);

print $list[ rand(@list) ], "\n";
Code
my @list = ('a', 'list', 'of', 'random', 'item's);

print $list[ rand(@list) ], "\n";
Comments bubble
In scalar context (such as the call to rand), an array evaluates to the length.
Comments bubble
In scalar context (such as the call to rand), an array evaluates to the length.
Code
$x[ array_rand($x) ]
Code
$x[ array_rand($x) ]
Comments bubble
array_rand returns the key, and we want the value.
Comments bubble
array_rand returns the key, and we want the value.
Doc URL
http://php.net/array_rand
Doc URL
http://php.net/array_rand
Imports
#include <stdlib.h>
Imports
#include <stdlib.h>
Code
x[rand() % x_length];
Code
x[rand() % x_length];
Comments bubble
rand needs to be initialized by calling void srand(unsigned int);
Comments bubble
rand needs to be initialized by calling void srand(unsigned int);
Imports
import "math/rand"
Imports
import "math/rand"
Code
x[rand.Intn(len(x))]
Code
x[rand.Intn(len(x))]
Origin
http://rosettacode.org/wiki/Pick_random_element#Go
Origin
http://rosettacode.org/wiki/Pick_random_element#Go
Demo URL
http://play.golang.org/p/hTw7pc7SN-
Demo URL
http://play.golang.org/p/hTw7pc7SN-
Imports
import random
Imports
import random
Code
random.choice(x)
Code
random.choice(x)
Imports
import java.util.Random;
Imports
import java.util.Random;
Code
x.get(new Random().nextInt(x.size()))
Code
x.get(new Random().nextInt(x.size()))
Origin
http://rosettacode.org/wiki/Pick_random_element#Java
Origin
http://rosettacode.org/wiki/Pick_random_element#Java