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

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: number, cols: number): number[][] {
    const matrix: number[][] = Array.from(
        { length: rows },
        (): number[] => Array(cols).fill(0)
    );
    
    return matrix;
}

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

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

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

    const matrix: number[][] = allocateMatrix(rows, cols);

    // Use a Set to ensure unique positions
    const chosen: Set<number> = new Set<number>();

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

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

    return matrix;
}

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

const result: number[][] = generateRandomMatrix(rows, cols, numberOfOnes);
printMatrix(result);



/*
run:

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

*/

 



answered Aug 20 by avibootz
...