user8575751
user8575751

Reputation:

Generate pairs of random integers in a grid (2D Array) python

I have been asked to make a number matching game for a school project, which involves generating random numbers in a grid. I have managed to generate the grid full of random numbers, but I need them to be in pairs so that they can be matched. Any help would be greatly appreciated. Here is my code so far:

def play(): import random

sizeofgrid()

board = []

showboard = []

for row in range(gridsize):
    board.append([])
    for column in range(gridsize):
        board[row].append(random.randint(0, 9))

def print_board(board):
    for row in board:
        print(' '.join([str(i) for i in row]))

showboard = [['O' for _ in range(gridsize)] for _ in range(gridsize)]

print_board(showboard)
print_board(board)

Upvotes: 0

Views: 1723

Answers (2)

aghast
aghast

Reputation: 15310

You need to change your approach. You can try one of two things:

  1. Start with an empty board. Generate a random number, then generate two random locations on the board. Keep re-generating until you find an empty slot, twice. Put the random number into both locations.

    for _ in range(width * height // 2):
        number = pick_random_number()
        loc1 = find_random_empty_spot()
        board[loc1.row][loc1.col] = number
        loc2 = find_random_empty_spot()
        board[loc2.row][loc2.col] = number
    
  2. Compute how many locations will need to be filled. Generate a N/2 random numbers, put each random number into a list, twice. Now, shuffle the list, and then loop over the board, inserting items from the list into the board.

    num_picks = width * height // 2
    picks = []
    
    for _ in range(num_picks):
        number = pick_random_number()
        picks.extend([number, number])
    
    random.shuffle(picks)
    
    for row in range(height):
        for col in range(width):
            board[row][col] = picks.pop()
    

Either of these approaches will get you the paired behavior you want. Which one you choose is a matter of comfort.

Upvotes: 0

Jared Goguen
Jared Goguen

Reputation: 9010

One approach might be to generate half of the numbers you need and then double that list. Then, shuffle the desired values and resize them into a grid.

from random import randint, shuffle

size = 4 # must be even
pairs = size**2/2

pool = range(pairs) * 2
# [0, 1, 2, 3, 4, 5, 6, 7, 
#  0, 1, 2, 3, 4, 5, 6, 7]

shuffle(pool)

grid = [pool[i:i+size] for i in range(0, size**2, size)]
# [[4, 5, 0, 7], [1, 7, 3, 5], [2, 1, 2, 6], [4, 0, 3, 6]]

Upvotes: 1

Related Questions