generate a random array in go

To generate a random array in Go, you can use the math/rand package and the time package. You need to set a seed value before generating random numbers so that the numbers are truly random. Here's an example code snippet:

main.go
package main

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

func main() {
    // set a seed value using the current time
    rand.Seed(time.Now().Unix())

    var arr [10]int

    // fill the array with random numbers
    for i := 0; i < len(arr); i++ {
        arr[i] = rand.Intn(100)
    }

    // print the array
    fmt.Println(arr)
}
342 chars
23 lines

In this example, we first set a seed value using the current time. Then, we declare an array of size 10 and fill it with random integers using the rand.Intn() function, which generates a random integer between 0 and the argument passed to it minus one. Finally, we print the generated array using fmt.Println().

related categories

gistlibby LogSnag