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.go432 chars25 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