Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to create an M x N matrix with random numbers in Go

1 Answer

0 votes
package main

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

const (
    ROWS = 4
    COLS = 5
)

// Print matrix to console
func printMatrix(matrix [][]int) {
    for _, row := range matrix {
        for _, val := range row {
            fmt.Printf("%4d", val)
        }
        fmt.Println()
    }
}

// Generate a random integer between min and max inclusive
func generateRandomInteger(min, max int) int {
    return rand.Intn(max-min+1) + min
}

// Generate a rows x cols matrix filled with random integers
func generateRandomMatrix(rows, cols int) [][]int {
    rand.Seed(time.Now().UnixNano())
    matrix := make([][]int, rows)
    for i := 0; i < rows; i++ {
        matrix[i] = make([]int, cols)
        for j := 0; j < cols; j++ {
            matrix[i][j] = generateRandomInteger(1, 100)
        }
    }
    
    return matrix
}

func main() {
    matrix := generateRandomMatrix(ROWS, COLS)
    printMatrix(matrix)
}



/*
run:
    
  71  27  88  61  86
  76  22  60  99  57
  49  97  13  55   7
  22  80  30  32  19
    
*/

 



answered Nov 22, 2025 by avibootz
...