Welcome, guest | Sign In | My Account | Store | Cart

This program can solve and create sudoku puzzles

Python, 203 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203``` ```#!/usr/bin/python # TODO: Make solve function faster!!! Have it check for singles, doubles, # triples, and quads both naked and hidden from random import random def rand(lst): "returns a random element in list or integer" if type(lst)==type([]): return lst[int(random()*len(lst))] elif type(lst)==type(0): return int(random()*lst) else: raise Exception,"don't know what do do with type %s!!!"%type(lst) def reorder(lst): "reorders a list to a random order" ret=[] for item in lst: ret.insert(rand(len(ret)),item) return ret def row(row,puzzle): return puzzle[row*9:row*9+9] def col(col,puzzle): ret=[] for i in range(9): ret.append(row(i,puzzle)[col]) return ret def box(box,puzzle): x=box%3 if box<3: y=0 elif box<6: y=1 else: y=2 ret=[] for i in range(3): ret.extend(row(y*3+i,puzzle)[x*3:x*3+3]) return ret def remaining(wcb): ret=[] for i in range(1,10): if not i in wcb: ret.append(i) return reorder(ret) # does not significantly slow program # and allows for generation of random puzzles def coordToBox(x,y): box=0 if x<3: pass elif x<6: box+=1 else: box+=2 if y<3: pass elif y<6: box+=3 else: box+=6 return box def coordToLinear(x,y): return y*9+x def linearToCoord(index): y=8 for i in range(9): if index

This program is somewhat unfinished, so I left my comments in there (including debugging ones) for anybody who wants to improve it. It does, however, work, so feel free to use it. The "TODO:" at the top refers to implementing a few different methods of solving sudoku puzzles in order to reduce the brute force used by the program.

brano sobotka 15 years, 7 months ago

or better random.shuffle(lst)

brano sobotka 15 years, 7 months ago

try lst = random.sample(lst, len(lst)) instead of def reorder(lst): ... ... ...

Collin Stocks (author) 15 years, 6 months ago

Thank you for the helpful comment. However, I have moved on to bigger and better things, and seeing as this project was "just for fun", I really cannot be bothered changing anything about it. Feel free to start an open source project around it if you so desire.

 Created by Collin Stocks on Fri, 12 Sep 2008 (MIT)