user3608028
user3608028

Reputation: 37

Generating random values in a Python list that don't repeat in the same index

I am making a program where I need to generate random values into a list. The user is asked to enter how many random values (chests - represented by the letter 'T') they would like to generate onto a 2D grid. The problem is that when the user types '8' as the number of random 'chests' they would like to generate, sometimes only 5 or 6 chests are generated to the grid (probably because the random integers repeat onto the grid and don't index at unique points in the grid). The number of chests are never accurately represented to the grid. How can I ensure all random values are assigned to unique indexes on the 2D grid?

    def chests():
        global chest
        chest = int(input("How many chests would you like in the game?"))
        for i in range(0,chest):
            board[randint(0, 4)][randint(0, 4)] = "T"


        return board

Upvotes: 2

Views: 74

Answers (1)

mgilson
mgilson

Reputation: 309929

It seems to me that you need to generate all of the possible indices and then randomly choose a "population":

import itertools
import random
chest_count = 8
BOARD_SIZE = 4
indices = list(itertools.product(range(BOARD_SIZE), repeat=2))
chest_locations = random.sample(indices, chest_count)
for i, j in chest_locations:
     board[i][j] = 'T'

This ends up being O(BOARD_SIZE^2). There are more sophisticated methods -- e.g. rather than needing to generate the entire board's indices, you could sample a population of a flattened board and then generate the indices after that:

locations = random.sample(range(BOARD_SIZE * BOARD_SIZE), chest_count)  # xrange on python2.x
for location in locations:
    j, i = divmod(location, BOARD_SIZE)
    board[i][j] = 'T'

This ends up being O(chest_count) which could be much smaller than the board size -- However, I doubt that your board is actually big enough to matter :-).

Upvotes: 6

Related Questions