Ad

Only The First Array Inside A 2D Array Being Updated By Function

I have written this code below to create a randomised sudoku puzzle grid:

import time
import random
import math

sudoLine = [0,0,0,0,0,0,0,0,0]

#Creating mainGrid, this is a blank sudoku grid which I will place the contents of the possibleNums array into in a random order for each line.
mainGrid = [

    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],

]

possibleNums = [1,2,3,4,5,6,7,8,9]
i = 0

#Grabbing the length of the possibleNums array and reducing it by 1 to get the index position of the last element.
length = len(possibleNums) - 1

def LineFill(line,nums,count):
    length = len(nums) - 1
    i = 0
    while length > 0:
        length = len(nums) - 1
        r = random.randint(0,length)
        line[i] = nums[r]
        nums.pop(r)
        i += 1
    return line

n=0

This while loop is then below that, and cycles through mainGrid, changing the array that is being filled each time:

while n in range(0,len(mainGrid)):
    mainGrid[n] = LineFill(mainGrid[n],possibleNums,i)
    n += 1

print(mainGrid)

When I run it, only the first line of the sudoku grid is filled, meaning only the first array in the list is being updated, even though the while loop should cycle through them all.

Could someone please point out the error in my logic?

Thanks.

Ad

Answer

Your line nums.pop() is the problem. You are passing possibleNums as the LineFill argument nums. So nums is just a reference to possibleNums. After you've filled one line, possibleNums is an empty list.

If your intent is to randomly populate a grid of numbers with no duplicates on any given row, here's a much easier approach:

In [1]: import random

In [2]: [random.sample(range(1, 10), 9) for _ in range(9)]
Out[2]:
[[3, 9, 8, 1, 2, 5, 6, 4, 7],
 [6, 7, 3, 9, 2, 5, 8, 1, 4],
 [4, 1, 9, 2, 7, 3, 5, 6, 8],
 [3, 5, 9, 4, 2, 1, 7, 8, 6],
 [7, 2, 8, 6, 1, 9, 4, 5, 3],
 [1, 8, 5, 9, 4, 6, 2, 7, 3],
 [8, 7, 1, 9, 2, 5, 3, 4, 6],
 [7, 6, 1, 5, 4, 2, 9, 3, 8],
 [7, 8, 4, 2, 5, 1, 6, 3, 9]]

Note that this method doesn't produce a valid Sudoku solution (it's theoretically possible, but the odds are... not in your favor) -- but it doesn't seem like that's what you're trying to do anyway.

Ad
source: stackoverflow.com
Ad