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

1 Answer

0 votes
import Foundation

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

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

// Allocate a rows×cols matrix initialized to zero
func allocateMatrix(rows: Int, cols: Int) -> [[Int]] {
    // Array(repeating:) keeps the code compact and expressive
    Array(repeating: Array(repeating: 0, count: cols), count: rows)
}

// Print the matrix
func printMatrix(_ matrix: [[Int]]) {
    for row in matrix {
        print(row.map(String.init).joined(separator: " "))
    }
}

// Generate N random 1s in a zero-based matrix
func generateRandomMatrix(rows: Int, cols: Int, count: Int) -> [[Int]] {
    let total = rows * cols

    if count > total {
        fatalError("Requested more 1s than available cells.")
    }

    var matrix = allocateMatrix(rows: rows, cols: cols)

    // Use a Set to ensure unique positions
    var chosen = Set<Int>()

    // Draw unique positions
    while chosen.count < count {
        let index = Int.random(in: 0..<total)
        chosen.insert(index)
    }

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

    return matrix
}

// Example usage
let rows = 5
let cols = 7
let numberOfOnes = 10

let result = generateRandomMatrix(rows: rows, cols: cols, count: numberOfOnes)
printMatrix(result)



/*
run:

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

*/

 



answered Aug 21 by avibootz
...