Logo

Programming-Idioms

History of Idiom 11 > diff from v35 to v36

Edit summary for version 36 by :
Restored version 34

Version 35

2016-02-18, 16:57:56

Version 36

2016-02-18, 17:20:00

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.

Imports
using System;
using System.Collections.Generic;
Imports
using System;
using System.Collections.Generic;
Code
x[new Random().Next(x.Count)];
Code
x[new Random().Next(x.Count)];
Imports
import scala.util.Random
Imports
import scala.util.Random
Code
val x = List(1, 2, 3, 4)
x.apply(Random.nextInt(x.size))
// apply can be called without the name or dot
// x(Random.nextInt(x.size))
Code
val x = List(1, 2, 3, 4)
x.apply(Random.nextInt(x.size))
// apply can be called without the name or dot
// x(Random.nextInt(x.size))
Imports
uses classes;
Imports
uses 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
Imports
import "math/rand"
Imports
import "math/rand"
Code
x[rand.Intn(len(x))]
Code
x[rand.Intn(len(x))]
Doc URL
https://golang.org/pkg/math/rand/#Intn
Doc URL
https://golang.org/pkg/math/rand/#Intn
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-