How to randomly place a random value in each row of an 8x8 int list with zero values in Python

1 Answer

0 votes
import random

# Board size constant for readability
BOARD_SIZE = 8

def initialize_board(board):
    """
    initialize_board:
      - Sets all values in the 8x8 array to zero
      - For each row:
          * randomly selects one column (0..7)
          * places a random integer (1..100) in that column
    """
    for row in range(BOARD_SIZE):

        # Set entire row to zero
        for col in range(BOARD_SIZE):
            board[row][col] = 0

        # Choose a random column index
        random_col = random.randint(0, BOARD_SIZE - 1)

        # Place a random non-zero value (1..100)
        board[row][random_col] = random.randint(1, 100)


def print_board(board):
    """
    print_board:
      - Prints the 8x8 board in a readable grid format
    """
    for row in board:
        print(" ".join(str(value) for value in row))


def main():
    # Create an 8x8 board initialized to zero
    board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]

    initialize_board(board)
    print_board(board)


if __name__ == "__main__":
    main()


"""
run:

0 0 0 0 0 0 0 95
0 0 0 0 0 95 0 0
0 28 0 0 0 0 0 0
0 0 17 0 0 0 0 0
0 82 0 0 0 0 0 0
0 0 0 0 0 93 0 0
0 0 0 52 0 0 0 0
0 0 0 75 0 0 0 0

"""

 



answered 2 days ago by avibootz

Related questions

...