get a sample of 5 elements from an array in go

To get a sample of 5 elements from an array in Go, you can use the math/rand package to generate 5 random indices and then select the values at those indices from the array.

Here's an example code snippet:

main.go
package main

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

func main() {
    // Seed the random number generator with the current time
    rand.Seed(time.Now().Unix())

    array := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sample := make([]int, 5)

    for i := 0; i < 5; i++ {
        randIndex := rand.Intn(len(array))
        sample[i] = array[randIndex]
    }

    fmt.Println("Sample:", sample)
}
408 chars
23 lines

In this example, we create an array of 10 integers and a slice of integers to hold our sample of 5 elements. We then loop 5 times, generating a random index within the bounds of the array and selecting the value at that index to add to our sample. Finally, we print out the resulting sample.

related categories

gistlibby LogSnag