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

1 Answer

0 votes
import random

"""
    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 helper set.
    - Convert each chosen flat index back to (row, col).
    - This avoids repeatedly searching for empty cells and keeps the logic simple.
"""

# Print the matrix
def print_matrix(matrix):
    for row in matrix:
        print(" ".join(str(v) for v in row))


# Allocate a rows×cols matrix initialized to zero
def allocate_matrix(rows, cols):
    # List comprehension keeps the code compact and expressive
    return [[0 for _ in range(cols)] for _ in range(rows)]


# Generate N random 1s in a zero-based matrix
def generate_random_matrix(rows, cols, count):
    total = rows * cols

    if count > total:
        raise ValueError("Requested more 1s than available cells.")

    matrix = allocate_matrix(rows, cols)

    # Use a set to ensure unique positions
    chosen = set()

    # Draw unique positions
    while len(chosen) < count:
        index = random.randrange(total)
        chosen.add(index)

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

    return matrix


# Example usage
if __name__ == "__main__":
    rows = 5
    cols = 7
    number_of_ones = 10

    result = generate_random_matrix(rows, cols, number_of_ones)
    print_matrix(result)



"""
run:

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

"""

 



answered Aug 20 by avibootz
...