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

One way to get a sample of 5 elements from an array in Go without replacement is to use the math/rand package and its Perm function. Here's an example:

main.go
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())

	original := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	n := len(original)

	perm := rand.Perm(n) // Random permutation of the indexes
	
	sampleSize := 5
	sample := make([]int, sampleSize)
	for i := 0; i < sampleSize; i++ {
		sample[i] = original[perm[i]] // Pick the first 5 elements of the permuted array
	}

	fmt.Println(sample)
}
432 chars
25 lines

First, we seed the random generator with the current time to ensure different random sequences on each run. Then, we create a slice original with the elements we want to sample from. Next, we get a random permutation of the indexes 0-9 using rand.Perm(n) and store it in perm.

Finally, we create an empty slice sample of size 5 and fill it with the first 5 elements of the permuted array by indexing into original with the indexes in perm.

The output of the program will be a random sample of 5 elements from original, without replacement.

gistlibby LogSnag