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

1 Answer

0 votes
/*
    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 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
function allocateMatrix(rows, cols) {
    // Array.from keeps the code expressive and clear
    return Array.from({ length: rows }, () => Array(cols).fill(0));
}

// Print the matrix
function printMatrix(matrix) {
    for (const row of matrix) {
        console.log(row.join(" "));
    }
}

// Generate N random 1s in a zero-based matrix
function generateRandomMatrix(rows, cols, count) {
    const total = rows * cols;

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

    const matrix = allocateMatrix(rows, cols);

    // Use a Set to ensure unique positions
    const chosen = new Set();

    // Draw unique positions
    while (chosen.size < count) {
        const index = Math.floor(Math.random() * total);
        chosen.add(index);
    }

    // Convert flat indices to (row, col)
    for (const index of chosen) {
        const r = Math.floor(index / cols);
        const c = index % cols;
        matrix[r][c] = 1;
    }

    return matrix;
}

// Example usage
const rows = 5;
const cols = 7;
const numberOfOnes = 10;

const result = generateRandomMatrix(rows, cols, numberOfOnes);
printMatrix(result);



/*
run:

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

*/

 



answered Aug 20 by avibootz
...