生成一个随机的(高度x宽度)网格,以便对于每个坐标(i,j),在一行或列中不可能有三个连续的相同颜色。
生成( int:宽度,int:高度,列表:颜色)
示例:
getvalidMatrix(3, 3, [0, 1, 2])
output:
[
[1, 2, 1],
[1, 0, 2],
[0, 1, 2],
]import random
def getvalidMatrix(length,width,colors):
map = dict()
for i in range(len(colors)):
map[colors[i]]=i
res = [[0] * length] * width
for i in range(length):
for j in range(width):
end = len(colors)
if i - 1 >= 0 and i - 2 >= 0 and res[i-1][j] == res[i-2][j]:
index = map[res[i-1][j]]
colors[index] = colors[end]
colors[end] = map[res[i-1]][j]
end -= 1
if j - 1 >= 0 and j - 2 >= 0 and res[i][j-1] == res[i][j-2]:
index = map[res[i][j-1]]
colors[index] = colors[end]
colors[end] = map[res[i][j-1]]
end -= 1
next=random.randint(0,end)
res[i][j] = colors[next]
return res
if __name__ == '__main__':
length = 3
width = 3
colors = [0,1,2]
print(getvalidMatrix(length, width, colors))我得到了IndexError: list索引超出了上面的代码范围。为了避免IndexError,我应该修复代码的哪一部分?
发布于 2022-10-17 05:52:43
虽然我没有完全理解用于解决问题的de算法,但我可以看到您犯了一些错误:
list_var[a][b]而不是list_var[b][a]。这可以在for循环中解决。zero-indexed.colors:colors[end] = ...,但是变量end初始化为end = len(colors),即值1单位大于允许的最大索引,请记住,列表是错误放置的结束括号。这是修正后的代码。运行一个文件diff来查看我所做的更改。我不能保证它现在解决了你所遇到的问题,但是你遇到的错误已经消失了。
import random
def getvalidMatrix(length,width,colors):
map = dict()
for i in range(len(colors)):
map[colors[i]]=i
res = [[0] * length] * width
for i in range(width):
for j in range(length):
end = len(colors)-1
if i - 1 >= 0 and i - 2 >= 0 and res[i-1][j] == res[i-2][j]:
index = map[res[i-1][j]]
colors[index] = colors[end]
colors[end] = map[res[i-1][j]]
end -= 1
if j - 1 >= 0 and j - 2 >= 0 and res[i][j-1] == res[i][j-2]:
index = map[res[i][j-1]]
colors[index] = colors[end]
colors[end] = map[res[i][j-1]]
end -= 1
next=random.randint(0,end)
res[i][j] = colors[next]
return res
if __name__ == '__main__':
length = 3
width = 3
colors = [0,1,2]
print(getvalidMatrix(length, width, colors))https://stackoverflow.com/questions/74051432
复制相似问题