How to fill a matrix with 1 and 0 in random locations with Go

1 Answer

0 votes
package main

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

const (
    ROWS = 5
    COLS = 4
)

func fillMatrixWithRandom0And1(matrix [][]int, rows, cols int) {
    rand.Seed(time.Now().UnixNano())
    
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            matrix[i][j] = rand.Intn(2) // Generates either 0 or 1
        }
    }
}

func printMatrix(matrix [][]int, rows, cols int) {
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            fmt.Print(matrix[i][j], " ")
        }
        fmt.Println()
    }
}

func main() {
    matrix := make([][]int, ROWS)
    for i := range matrix {
        matrix[i] = make([]int, COLS)
    }

    fillMatrixWithRandom0And1(matrix, ROWS, COLS)
    
    printMatrix(matrix, ROWS, COLS)
}



/*
run:

1 1 1 0 
1 0 1 0 
1 1 0 0 
0 0 1 1 
0 0 0 0 

*/

 



answered Jan 26, 2025 by avibootz

Related questions

1 answer 89 views
1 answer 100 views
1 answer 91 views
1 answer 86 views
1 answer 89 views
...