简体   繁体   English

尝试在Python中使用随机数为数独创建矩阵

[英]Trying create a matrix for sudoku with random numbers in Python

I need to create a sudoku template, with it all filled. 我需要创建一个数独模板,并全部填充。 I need to do with random numbers, so I check if the number already exists in the row and in the column. 我需要处理随机数,因此我检查行和列中是否已经存在该数字。 The problem is that when a number is repeated in the column, it does not try another one, getting an infinite loop. 问题在于,当在列中重复一个数字时,它不会尝试另一个,从而导致无限循环。 Can Someone help me? 有人能帮我吗? Remembering that I am required to do with random numbers. 记住我需要处理随机数。

import random
matrix = [[None for i in range(9)] for j in range(9)]

def criarSdk():
    for l in range(9):
        for c in range(9):
            if matrix[l][c] is None:
                tmp3 = False
                print("linha l={}, coluna c={}".format(l,c))
                while tmp3 is False:
                    ale = random.randint(1, 9)
                    tmp1 = veriLine(matrix,ale, l)
                    tmp2 = veriCol(matrix,ale, c)
                    tmp3 = tmp1 and tmp2
                    if tmp3 is True:
                        matrix[l][c] = ale

def veriLine(vetor, value, line):
    tmp = True
    for c in range(9):
        if value == vetor[line][c]:
            tmp = False

    return tmp

def veriCol(vetor, value, col):
    tmp = True
    for l in range(9):
        if value == vetor[l][col]:
            tmp = False

    return tmp

criarSdk()
for i in range(9):
    print(matrix[i])

Your problem is not with the code, but with your algorithm. 您的问题不在于代码,而在于算法。

If you fill up a sudoku like this, you can end up in a situation where no digit can be filled in for some space. 如果这样填充数独,则可能会遇到无法在某些空间填充数字的情况。

Consider this: 考虑一下:

1 2 3 4 5 6 7 8 9
2 1 5 3 4 7 8 6 x

You can imagine the first line getting filled with random values (which happen to be in order) and then the values on the second line also getting filled in with random values, but what value to put in x? 您可以想象第一行被随机值填充(碰巧是按顺序排列),然后第二行的值也被随机值填充,但是要在x中输入什么值? You can't put in 9 , because it would conflict on the column. 您不能输入9 ,因为它会在列上发生冲突。 But you can't put in anything else either, since everything else is already on the line. 但是您也不能输入其他任何内容,因为其他所有内容都已在线上。

In this case, your code will loop endlessly, trying random numbers, but none of them will ever work. 在这种情况下,您的代码将无限循环,尝试使用随机数,但是它们都不起作用。

You need to look into backtracking and come up with a better solution. 您需要研究回溯并提出更好的解决方案。 Note that your requirement for randomly picking a number doesn't have to mean you keep calling random.randint() for a new option, you could also randomly pick from a set of numbers you haven't tried yet. 请注意,您需要随机选择一个数字并不一定意味着您继续为新选项调用random.randint() ,也可以从尚未尝试的一组数字中随机选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM