You can use the math/rand
package to generate a sequence of pseudo-random integers, which you can use to index into the array.
Here's an example function that takes an array and returns a slice containing a random sample of size
elements, with replacement:
main.go410 chars23 lines
In this example, the sampleWithReplacement
function takes an array (arr
) and a sample size (size
), and returns a slice containing size
random elements from arr
, selected with replacement.
In the loop, we generate a random integer between 0 and len(arr)
- 1 using rand.Intn
, and use it to index into the array to select a random element. We repeat this size
times to generate the sample.
You can run this code on the Go Playground here.
gistlibby LogSnag