首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成随机色板

生成随机色板
EN

Stack Overflow用户
提问于 2022-10-13 06:40:47
回答 1查看 49关注 0票数 0

生成一个随机的(高度x宽度)网格,以便对于每个坐标(i,j),在一行或列中不可能有三个连续的相同颜色。

生成( int:宽度,int:高度,列表:颜色)

示例:

代码语言:javascript
复制
getvalidMatrix(3, 3, [0, 1, 2])

output:

[

[1, 2, 1],

[1, 0, 2],

[0, 1, 2],

]
代码语言:javascript
复制
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,我应该修复代码的哪一部分?

EN

回答 1

Stack Overflow用户

发布于 2022-10-17 05:52:43

虽然我没有完全理解用于解决问题的de算法,但我可以看到您犯了一些错误:

  1. --您正在错误地检索多维列表元素,例如,list_var[a][b]而不是list_var[b][a]。这可以在for循环中解决。zero-indexed.
  2. A
  3. --您用这种方式索引变量colorscolors[end] = ...,但是变量end初始化为end = len(colors),即值1单位大于允许的最大索引,请记住,列表是错误放置的结束括号。

这是修正后的代码。运行一个文件diff来查看我所做的更改。我不能保证它现在解决了你所遇到的问题,但是你遇到的错误已经消失了。

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74051432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档