Search code examples
pythonlistnested-lists

i have a 2D list of any size of all "0" and want to randomly replace 10 of these with a "1"


I am making mine sweeper and have a 2D list representing a board that is always a square of user inputted size. It begins filled with zeroes and I want to replace x number of these with ones to represent a mines location. I need it to always make 10 mines never duplicate the same place and this is using the random library. I don't mind computational time is will be almost meaningless but i do want it to be elegant, all my past projects have been a jumbled mess of computer translated thoughts.

I think i have an aproximate solution in sudo code allong the lines of:

mines10 while mines is more than 1 chose a random row chose random column try change it if it change one less mine left to place

but this is very clunky i want a more elegant solution maby an inbuilt random function IDK that's why I'm asking


Solution

  • An simple one-liner approach would be to use itertools.product to generate a sequence of all the locations and random.sample to pick 10 unique elements from that sequence.

    Assuming the board is 5x5 and you want 10 items, that'd look like:

    >>> import itertools
    >>> import random
    >>> random.sample(list(itertools.product(range(5), repeat=2)), k=10)
    [(4, 1), (4, 3), (4, 2), (2, 1), (1, 2), (0, 4), (2, 4), (2, 0), (4, 0), (2, 3)]
    

    Note that building a list of all the locations may not be optimal if you have a ridiculously large board (although if you have a ridiculously large board, setting up the starting locations for the mines is likely to be the least of your worries). The optimal approach (i.e. not requiring you to build a list of all those tuples just to pick a subset of them) would be to represent each location as a single value in a range and then convert the values to tuples after calling sample:

    >>> [(n % 5, n // 5) for n in random.sample(range(5 * 5), 10)]
    [(0, 3), (0, 1), (1, 4), (3, 0), (3, 1), (3, 2), (0, 4), (1, 2), (4, 0), (1, 0)]