假设我有一个7x7网格:
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
如何在网格中的任何位置随机将0放在3行/ 3列中?
. . . . . . .
. . . . . . .
. . 0 0 0 . .
. . . . . . .
. . . . . 0 .
. . . . . 0 .
. . . . . 0 .
答案 0 :(得分:0)
随机化方向...水平或垂直。 然后你将两个数字随机化为“000”的位置,但这取决于方向。一个数字在范围(0,7)中,另一个在范围内(0,7-3)。 “-3”部分是这样的,它不会放在板外。
这是一些python代码......
from random import randint
def place_randomly(grid):
orientation = ['h', 'v'][randint(0, 1)] #randomly choose orientation
if orientation == 'h':
x = randint(0, 4)
y = randint(0, 6)
grid[y][x] = grid[y][x+1] = grid[y][x+2] = '0'
elif orientation == 'v':
x = randint(0, 6)
y = randint(0, 4)
grid[y][x] = grid[y+1][x] = grid[y+2][x] = '0'
print "XY:", x, y
def print_grid(grid):
for i in grid:
for j in i:
print j,
print ""
for i in range(10): # try it out 10 times
grid = [['.' for x in range(7)] for x in range(7)]
place_randomly(grid)
print_grid(grid)
print ""