How to generate N random 1s in a zero-based matrix with Go

1 Answer

0 votes
package main

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

/*
    Generate N random 1s in a zero-based matrix.

    Strategy:
    - Treat the matrix as a flat index space [0 .. rows*cols - 1].
    - Randomly pick unique positions using a map[ int ]bool to ensure uniqueness.
    - Convert each chosen flat index back to (row, col).
    - This avoids repeatedly searching for empty cells and keeps the logic simple.
*/

// allocateMatrix creates a rows×cols matrix initialized to zero.
func allocateMatrix(rows int, cols int) [][]int {
    matrix := make([][]int, rows)
    for r := 0; r < rows; r++ {
        matrix[r] = make([]int, cols) // automatically initialized to zero
    }

    return matrix
}

// printMatrix prints the matrix row by row.
func printMatrix(matrix [][]int) {
    for _, row := range matrix {
        for _, v := range row {
            fmt.Printf("%d ", v)
        }
        fmt.Println()
    }
}

// generateRandomMatrix places N random 1s in a zero-based matrix.
func generateRandomMatrix(rows int, cols int, count int) [][]int {
    total := rows * cols
    if count > total {
        panic("Requested more 1s than available cells.")
    }

    matrix := allocateMatrix(rows, cols)

    // Use a map to ensure unique positions
    chosen := make(map[int]bool)

    rand.Seed(time.Now().UnixNano())

    // Draw unique positions
    for len(chosen) < count {
        index := rand.Intn(total)
        chosen[index] = true
    }

    // Convert flat indices to (row, col)
    for index := range chosen {
        r := index / cols
        c := index % cols
        matrix[r][c] = 1
    }

    return matrix
}

func main() {
    rows := 5
    cols := 7
    numberOfOnes := 10

    result := generateRandomMatrix(rows, cols, numberOfOnes)
    printMatrix(result)
}


/*
run:

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

*/

 



answered Aug 20 by avibootz
...