import pprint, random
pp = pprint.PrettyPrinter(1)
grid = []
for x in range(6):
orbs = [0, 1, 2, 3, 4, 5]
random.shuffle(orbs)
y_list = []
for y in range(5):
y_list.append(orbs[y])
grid.append(y_list)
pp.pprint(grid)
好的,我已经写了上面的代码来打印6(R)x5(C)矩阵\板的2d数组。电路板中的每个坐标应在每个循环上随机生成,这就是我想要的。
现在,我无法绕过如何检查3-in-a-row匹配(仅垂直或水平),以便像这样的随机板永远不会发生它们。
我应该先创建电路板,然后先检查条件(3行)吗?或者,我应该在生成每行\列的条件下编码?是否有一个我应该看的python模块已经在这些方面做了什么?
编辑:
以下是一个不可接受的输出示例:
[[5, 2, 5, 2, 2],
[5, 4, 1, 5, 2],
[1, 1, 0, 5, 3],
[4, 4, 4, 0, 1],
[0, 5, 0, 0, 3],
[5, 3, 4, 2, 5]]
这是可以接受的:
[[4, 1, 4, 4, 5],
[1, 3, 0, 1, 4],
[1, 5, 4, 4, 0],
[5, 2, 0, 4, 3],
[5, 4, 2, 1, 0],
[0, 1, 5, 0, 4]]
答案 0 :(得分:0)
是的,这听起来最简单!我应该先创建电路板,然后先检查条件(3行)吗?
或者我应该在每个行\列的条件下编码生成它们吗?
我不会!那会更复杂。 =)
答案 1 :(得分:0)
numpy
> a = np.array(
[[5, 2, 5, 2, 2],
[5, 4, 1, 5, 2],
[1, 1, 0, 5, 3],
[4, 4, 4, 0, 1],
[0, 5, 0, 0, 3],
[5, 3, 4, 2, 5]])
> (a[:,:-2:] == a[:,1:-1:]) & (a[:,:-2:] == a[:,2::]) # start of horizontal runs
array([[False, False, False],
[False, False, False],
[False, False, False],
[ True, False, False],
[False, False, False],
[False, False, False]], dtype=bool)
> (a[:-2:,:] == a[1:-1:,:]) & (a[:-2:,:] == a[2::,:]) # start of vertical runs
> (a[:-2:,:-2:] == a[1:-1:,1:-1:]) & (a[:-2:,:-2:] == a[2::,2::]) # start of diagonal runs
您可以使用numpy.where(a[:,:-2:] == a[:,1:-1:]) & (a[:,:-2:] == a[:,2::])
来获取跑步开始的坐标。
答案 2 :(得分:0)
def validate(board):
Hdiff = np.abs(np.diff(board))
Vdiff = np.abs(np.diff(board.T))
kernel = np.ones((1,2))
test = convolve2d(Hdiff, kernel, 'valid')
test2 = convolve2d(Vdiff, kernel, 'valid')
x1,y1 = np.nonzero(test == 0)
y2,x2 = np.nonzero(test2 == 0)
if len(x1):
board[x1,y1] = np.random.randint(0, 5, len(x1))
if len(x2):
board[x2,y2] = np.random.randint(0, 5, len(x2))
if len(x1) or len(x2):
return validate(board)
else:
return board
myBoard = np.random.randint(0, 5, (6, 5))
myBoard[1,2:5] = [3, 3, 3]
myBoard[0:3, 0] = [1, 1, 1]
print myBoard
print validate(myBoard)
原文:
[[1 0 0 0 3]
[1 3 3 3 3]
[1 1 0 0 0]
[1 3 4 4 1]
[0 1 2 0 4]
[2 3 2 3 1]]
验证:
[[4 4 0 0 3]
[4 1 2 3 3]
[1 1 2 0 0]
[1 3 4 4 1]
[0 1 2 0 4]
[2 3 2 3 1]]
使用卷积检测无效的行\列。