Welcome, guest | Sign In | My Account | Store | Cart
NOTE: Recipes have moved! Please visit GitHub.com/activestate/code for the current versions.

This script views a sudoku problem as a 3-dimensional binary cube. It solves the sudoku problem by wiping away x,y,z points from this cube until the solution appears.

Python, 137 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""
This code is placed in the public domain. The author 
can be reached at anton.vredegoor@gmail.com

Last edit: Anton Vredegoor, 22-02-2006

A sudoku problem is represented by a binary cube, 
the x and y coordinates are the rows and columns of
the original sudoku, the z-coordinate is the value
(the "height") of a point in the sudoku grid.

We wipe away points until there are n**4  (81 if we
start with parameter n=3) binary points left in the cube,
which do not share points in the same x,y,or z 
"sight line" or nxn,z block.

The sudoku17 file that is read from is a list of sudoku
problems with 17 givens and can be found at:

http://www.csse.uwa.edu.au/~gordon/sudokumin.php

Thanks Gordon, for making this list available.

In each line there are 81 digits in range(10) and a 
linefeed. Here is the first line (0 means "unknown"):

000000010400000000020000000\
000050407008000300001090000\
300400200050100000000806000

I used vpython while developing the code in order to
visualize what was going on in the cube (some simple
differently colored spheres in 3d space helped a lot), 
but the final script doesn't need it. Still, I am awed by 
vpythons 3D stereo mode which the "crosseyed"
visualization trick. Keep up the good work.

Uncomment this line in function "test" to see
the sudoku grid output: 

for sol in sols: print sol
"""

n = 3
n2 = n*n
n4 = n2*n2
B = range(n)
R = range(n2)

class Node:
    
    def __init__(self,possibles): 
        S = self.possibles = possibles #set of possible points (3-tuples)
        all = self.all = self.clean() #list of all *lists* of points
        valid = self.isvalid = len(S)>=n4 and len(all)==n4*4
        self.issolved = valid and len(S)==n4 and max(map(len,all))==1
    
    def clean(self):
        #eliminate points until stable
        S = self.possibles
        while True:
            L = {},{},{},{}
            for x,y,z in S:
                r,c = x//n,y//n
                for Q,T in zip(L,((x,y),(x,z),(y,z),(r,c,z))):
                    Q[T] = Q.get(T,[]) +[(x,y,z)]
            all = []
            for Q in L:
                all.extend(Q.values())
            ns = len(S)
            for x in all:
                if len(x) == 1:                    
                    S -= friends(x[0])
            if ns == len(S):
                break
        return all
        
    def children(self):
        if self.isvalid and not self.issolved:
            #heuristic: choose shortest list of points
            pts = min((len(x),x) for x in self.all if len(x)>1)[1]
            for p in pts:
                yield Node(self.possibles-friends(p))

    def __repr__(self):
        S = self.possibles
        M = [['_' for i in R] for j in R]
        for i,j,k in S:
            if not S&friends((i,j,k)):
                M[i][j] = str(k+1)
        return '\n'+'\n'.join(map(''.join,M))

def friends(point, memo = {}):
    #points in the same sight line or nxnxz block
    try:
        return memo[point]
    except KeyError:        
        x,y,z = point
        res = set()
        for i in R:
            res.update([(i,y,z),(x,i,z),(x,y,i)])
        a,b = x//n*n,y//n*n
        res |= set((a+i,b+j,z) for i in B for j in B)
        res.discard((x,y,z))
        memo[point] = res
    return res

def solutions(N):
    #depth first search
    if N.issolved:
        yield N
    else:
        for child in N.children():
            for g in solutions(child):
                yield g

def readstring(s):
    Z = zip([(i,j) for i in R for j in R],map(int,s))
    givens = set((i,j,k-1) for (i,j),k in Z if k)
    possibles = set((i,j,k) for i in R for j in R for k in R)
    for p in givens:
        possibles -= friends(p)
    return possibles
        
def test():
    for i,line in enumerate(file('sudoku17')):
        N = Node(readstring(line.strip()))
        sols = list(solutions(N))
        if  i%10==0: print
        print i,
        #for sol in sols: print sol
        if len(sols) > 1:
            print 'more than one solution'
            break
        
if __name__=='__main__':
    test()

This is just a recreative exercise in reasoning about sudoku problems. This solver solves most problems without making any guesses, and for the remaining problems it uses only very few guesses. It could be made a lot faster with numerical python.

What I would like do do next is to wipe additional points by reasoning about "fields" having 2 or more points in common instead of only one, like this solver does. Does anyone know about the terminology that applies to such problems? Some wikipedia article writes about contingencies, but the algorithm one would use is not quite clear.

It seems Raymond Hettinger and me are trying to do the same things and come up with almost (but not quite) the same ideas. Anyway, I acknowledge his inspiration. But I think this solver uses less guesses, because it chooses its children out of more possible fields. It tries rows, columns, or regions in addition to trying to 'fill in a value' (which is analogous to deleting all but one value of a vertical column in this metaphor).

3 comments

Justin Shaw 11 years, 7 months ago  # | flag

Where are the vPython calls? I'd like to see the visualization you were using. Can you add back in the visual calls?

Anton Vredegoor (author) 11 years, 6 months ago  # | flag

The vpython code is in a separate script. I tried to put some vpython script in a comment window but it was not displayed correctly. Sorry.

Anton Vredegoor (author) 10 years, 8 months ago  # | flag

**OK, I found the

tag ...**

from visual import *

n = 3
n2 = n*n
B = range(n)
R = range(n2)

def show_friends(pt):
    for p in full():
        if list(p).count(0) >= 2:
            ball = sphere(pos=p, radius=.2,color=color.white)
    for p in friends(pt):
        ball = sphere(pos=p, radius=.3,color=color.yellow)
    ball = sphere(pos=pt, radius=.4,color=color.red)

def friends(point):
    x,y,z = point
    res = set()
    for i in R:   res.update([(i,y,z),(x,i,z),(x,y,i)])
    a,b = x//n*n,y//n*n
    res |= set((a+i,b+j,z) for i in B for j in B)
    res.discard((x,y,z))
    return res

def full():
    return set((i,j,k) for i in R for j in R for k in R)

def test():
    scene.center = n+1,n+1,n+1
    scene.stereo = 'passive'
    scene.stereodepth = 0
    scene.range = n2+2
    scene.up = -1,0,0
    scene.ambient = .5
    scene.fullscreen = 1
    show_friends((2,3,4))

if __name__=='__main__':
    test()
Created by Anton Vredegoor on Thu, 23 Feb 2006 (PSF)
Python recipes (4591)
Anton Vredegoor's recipes (11)

Required Modules

  • (none specified)

Other Information and Tasks