Home > OS >  Python problem with checking and filling 2D-list in a loop with True and False
Python problem with checking and filling 2D-list in a loop with True and False

Time:06-18

so I have a function generateSudoku() which should check my 2 Dimensional List which goes from [0][0] to [8][8] (81 fields), and fill in the fields with random numbers by following the rules of a sudoku game which is checked by kontrolleFeld()

kontrolleFeld() checks if the random generated number fits in to the field. If kontrolleFeld() is true then it goes on to the next field to check and fill in a number up to field [0][8] and then it starts from the next "row"( [1][0] ) to check so that it should check up all fields up to [8][8]. If its false then it checks the same field again with another int number.

but something is unfortunately wrong because sometimes it checks up to 2nd row and stops sometimes 3rd row and stops and sometimes only 1st row.

the kontrolleFeld() function which gives back True or False is working flawless. This isn't the problem. (I tested it with already given sudoku)

def generateSudoku():
    xcount = 0
    ycount = 0
    while xcount !=9:
        if ycount == 9:
            xcount = xcount  1
            ycount = 0
        else:
            while ycount !=9:
                zrand = random.randint(1,9)
                if kontrolleFeld(xcount,ycount,zrand):
                    s1[xcount][ycount]=zrand
                    ycount = ycount  1

CodePudding user response:

I think you are looking for something like this:

def generateSudoku():
    xcount = 0
    ycount = 0
    while xcount !=9:
        if ycount == 9:
            xcount = xcount  1
            ycount = 0
        else:
            while ycount !=9:
                while True:
                    zrand = random.randint(1,9)
                    if kontrolleFeld(xcount,ycount,zrand):
                        break
                s1[xcount][ycount]=zrand
                ycount = ycount  1

CodePudding user response:

Suppose the first 2 rows of your grid have been filled in as follows:

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

There is no value that can legally replace the ?, so your while True loop will never terminate.

  • Related