I have a board of a solved sudoku and I'm trying to randomly replace some of the elements with 0 to make a new puzzle. How do I do it?
board = [[2, 1, 3, 4],
[3, 4, 1, 2],
[1, 2, 4, 3],
[4, 3, 2, 1]]
You can use random.sample
to find n random coordinates to remove from the board. For example, the following will set 5 random cells to 0:
>>> import random
>>> empty_cells = random.sample([(i, j) for i in range(4) for j in range(4)], 5)
>>> for row, col in empty_cells:
... board[row][col] = 0
...
>>> board
[[2, 0, 3, 0], [3, 4, 0, 2], [1, 2, 0, 3], [4, 0, 2, 1]]