我无法修复我的代码,试图使用python 3x生成随机数独板

问题描述 投票:-4回答:1

这段代码能够生成一些行,但突然间我会进入一个无限循环。请有人修复此代码。

import numpy as np
import random


soduku = np.zeros(shape=(9,9))

for i in range(0,9,1):
    for j in range(0,9,1):
        while True:
            x = random.randint(1,9)
            if x not in soduku[i,:] and x not in soduku[:,j]:
                soduku[i,j] = x
                if j == 8: print(soduku[i,:])
                break
python
1个回答
0
投票

你的逻辑是错误的,因为你没有回溯的条款。看看你的内循环:

    # i and j are "given" at this point.
    while True:
        x = random.randint(1,9)     # grab a random number
        # Is it legal to put the number in this square?  If not, keep looping
        if x not in soduku[i,:] and x not in soduku[:,j]:
            soduku[i,j] = x
            if j == 8: print(soduku[i,:])
            break

现在让我们看看第二行末尾的一个简单情况,即部分填充:

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

我们想填补第二行的最后一个位置。但是,无论您在1-9范围内选择什么号码,该号码都已存在于该行或最后一列中。

您的程序无法备份并重试:它只是选择一个随机数并尝试将其放在那里。

你需要研究数独填充算法。这些可以在Stack Overflow和其他地方上线获得。

© www.soinside.com 2019 - 2024. All rights reserved.