2

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
2
  • Can you use numpy or do you need pure python implementation? Commented Nov 29, 2016 at 18:32
  • Pure Python implementation. Commented Nov 29, 2016 at 18:44

1 Answer 1

6

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 :-).

Sign up to request clarification or add additional context in comments.

4 Comments

Very elegant solution
This second one was what I was typing when you posted. Nice work, both ways.
@Prune -- Yeah. I thought it was going to be harder to implement but then I remembered divmod. It turns out that it does exactly what we want it to for a 2D board. Neat.
Thanks for this solution. It looks neat and tidy. Appreciate you guys taking the time to comment and help out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.