generate a random (height x width) grid such that for every coordinate (i, j), there can be no three consecutive same colors in a row or in a column.
generate(int: width, int: height, list: colors)
Example:
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))
I got IndexError: list index out of range with the code above. Which part of the code should I fix in order to avoid the IndexError?
Aucun commentaire:
Enregistrer un commentaire