get a sample of 5 elements from an array with replacement in go

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.go
package main

import (
    "fmt"
    "math/rand"
)

func sampleWithReplacement(arr []interface{}, size int) []interface{} {
    sample := make([]interface{}, size)

    for i := 0; i < size; i++ {
        sample[i] = arr[rand.Intn(len(arr))]
    }

    return sample
}

func main() {
    arr := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sample := sampleWithReplacement(arr, 5)
    fmt.Println(sample)
}
410 chars
23 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