Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Generate a random array/slice of n integers in Go (Golang)

Posted on April 2, 2020April 2, 2020 by admin

Table of Contents

  • Overview
  • Code:

Overview

math/rand package of GO provides a Perm method that can be used generate the pseudo-random slice of n integers. The array will be pseudo-random permutation of the integers in the range [0,n).

To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang
Below is the signature of the function. It takes a number n as input and returns the permuted slice.

func Perm(n int) []int

Code:

package main

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

func main() {
    //Provide seed
    rand.Seed(time.Now().Unix())

    //Generate a random array of length n
    fmt.Println(rand.Perm(10))
    fmt.Println(rand.Perm(10))
}

Output:

[6 0 1 5 9 4 2 3 7 8]
[9 8 5 0 3 4 6 7 2 1]
  • array
  • go
  • golang
  • random
  • slice
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme