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

1 Answer

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

    Strategy:
    - Treat the matrix as a flat index space [0 until rows*cols].
    - Randomly pick unique positions using a MutableSet 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
fun allocateMatrix(rows: Int, cols: Int): Array<IntArray> {
    // IntArray keeps memory compact and fast
    return Array(rows) { IntArray(cols) { 0 } }
}

// Print the matrix
fun printMatrix(matrix: Array<IntArray>) {
    matrix.forEach { row ->
        println(row.joinToString(" "))
    }
}

// Generate N random 1s in a zero-based matrix
fun generateRandomMatrix(rows: Int, cols: Int, count: Int): Array<IntArray> {
    val total = rows * cols

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

    val matrix = allocateMatrix(rows, cols)

    // Use a MutableSet to ensure unique positions
    val chosen: MutableSet<Int> = mutableSetOf()

    // Draw unique positions
    while (chosen.size < count) {
        val index = (0 until total).random()   // Kotlin's expressive random API
        chosen += index
    }

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

    return matrix
}

// Example usage
fun main() {
    val rows = 5
    val cols = 7
    val numberOfOnes = 10

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



/*
run:

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

*/

 



answered Aug 21 by avibootz
...