473,785 Members | 2,607 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sudoku dictionary attack

Thought I'd offer a method for solving all possible 9x9 sudoku puzzles
in one go. It'll takes a bit of time to run however (and 9x9 seems to
be about as big as is reasonably possible before combinatorial
explosion completely scuppers this type of program)...

Basic idea:-

Start with a grid initialised with:

123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678

Note that all rows and columns contain all 9 digits (but that the
sub-tiles aren't correct for a sudoku solution).

Next write a program which permutes all 9 columns, and then for each of
those permutations permutes the last 8 rows. This will, I believe,
generate all possible grids with no digit repetitions in any row or
column. It will generate 14,631,321,600 (9!*8!) possible sudoku
candidates. Finally, check each candidate to see if any 3x3 subtile has
a repeated digit in it and discard as soon as a repeat is found (sooner
the better). Any that come through unscathed get written as a 82 (81 +
lf) char string to an output file.

I've written a short program (in Python; see below) that tries out this
idea. Indications are that my HP nc6000 laptop can check around 30,000
candidates/sec and that c.0.15% of them are valid sudoku solutions.
That means it would take around 6.5 days to generate the between 20-30
million possible sudoku solutions it will find. That would require
around 2GB in uncompressed disk storage. Gzip does a VERY good job of
compressing files containing this type of data -- so I'd expect well
over 80% compression (might even fit on a CD then).

Once you've generated the solution data then comes the fun of searching
it efficiently which I leave as an exercise for the reader :-)

Regards, sub1ime_uk (at) yahoo (dot) com

=============== =============== =============== =============== ======
#!python
#
# sudoku.py - generate all valid sudoku solutions
#
# Usage: sudoku <N> <S>
# eg: sudoku 9 3
# Whare:-
# N is the grid size (ie 9 for 9x9)
# S is the sub-tile size (3 for 3x3)
#
# (c) 2005 sub1ime_uk (at) yahoo (dot) com
#
import sys
from gzip import GzipFile
from time import time

def permute(s):
if len(s)==0: return
if len(s)==1:
yield s
return
for i in range(len(s)):
for t in permute(s[:i]+s[i+1:]):
yield s[i:i+1]+t
return

def populate(sz, ini):
tile = []
for i in range(sz):
tile.append([])
for j in range(sz):
x = chr((i+j)%sz+or d(ini))
tile[i].append(x)
return tile

def subtilesok(t, c, r, n, s):
for x in range(0, n, s):
for y in range(0, n, s):
d = {}
for i in range(s):
cn = c[x+i]
for j in range(s):
rn = r[y+j]
d[t[cn][rn]] = 1
if len(d.keys())!= n: return 0
return 1

def displaytile(t, c, r, lf):
lfstr=''
print
for i in r:
row = []
for j in c:
row.append(t[j][i])
r=''.join(row)
lfstr += r
print " ",r
print
lf.write(lfstr+ "\n")

def fact(n):
if n<2: return 1
return n*fact(n-1)

if __name__ == '__main__':
st = time()
logf = GzipFile("c:\\t emp\\sudoku.gz" , "w")
N=int(sys.argv[1])
S=int(sys.argv[2])
estimate = fact(N)*fact(N-1)
if N!=S*S:
print "Subtile size", S, "not sqrt of tile size", N
sys.exit(1)
cols = [x for x in range(N)]
rows = [x for x in range(1, N)]
primarytile = populate(N, '1')
count = 0
answc = 0
for colp in permute(cols):
for rowp in permute(rows):
count += 1
if subtilesok(prim arytile, colp, [0]+rowp, N, S):
answc += 1
ct = time()
et=ct-st
if et>0.0:
print "Found: %d out of %d (%.2f%%) checked" % (answc, count,
(answc*100./count))
print "Progress: %.2f%%" % ((count*100./estimate))
print "Elapsed time: %.2f secs, checked: %d/s, found %d/s." %
(et, (count/et), (answc/et))
print "Estimate time to go: %.2f hours" %
((estimate-count)*et/(count*3600.))
else:
print "%d / %d (%5.2f%%)" % (answc, count,
(answc*100./count))
displaytile(pri marytile, colp, [0]+rowp, logf)
print
print "Checked", count,"tiles. Found", answc,"answers. "
logf.close()
sys.exit()
=============== =============== =============== =============== =======

Jul 19 '05 #1
5 2645


su********@yaho o.com wrote:
Thought I'd offer a method for solving all possible 9x9 sudoku puzzles
in one go. It'll takes a bit of time to run however (and 9x9 seems to
be about as big as is reasonably possible before combinatorial
explosion completely scuppers this type of program)...

Basic idea:-

Start with a grid initialised with:

123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678

Note that all rows and columns contain all 9 digits (but that the
sub-tiles aren't correct for a sudoku solution).

Next write a program which permutes all 9 columns, and then for each of
those permutations permutes the last 8 rows. This will, I believe,
generate all possible grids with no digit repetitions in any row or
column. It will generate 14,631,321,600 (9!*8!) possible sudoku
candidates. Finally, check each candidate to see if any 3x3 subtile has
a repeated digit in it and discard as soon as a repeat is found (sooner
the better). Any that come through unscathed get written as a 82 (81 +
lf) char string to an output file.


I'm having trouble coming up with anything that fits this grid:

...12.....
...2x.....
..........
..........
..........
..........
..........
..........
..........

where x is not 3, by permuting columns, then rows. You may also have
to permute the numbers. Although, even then, x=1 is still impossible.

Jul 19 '05 #2
Has some one an sodoku-task-generator?
Here another solutions-ways:
http://www.python-forum.de/viewtopic.php?t=3378

--
<!--Olliminatore-->input<?/>
Jul 19 '05 #3
"Oliver Albrecht" <55*********@ t-online.de> wrote ...
Has some one an sodoku-task-generator?


Sudoku puzzles can be generated (and solved) online at
http://act365.com/sudoku/
Jul 19 '05 #4
On Mon, 20 Jun 2005 23:30:27 +0200, Oliver Albrecht
<55*********@ t-online.de> wrote:
Has some one an sodoku-task-generator?
Here another solutions-ways:
http://www.python-forum.de/viewtopic.php?t=3378


It's presumably easy to turn a solver into a generator.

Start with a random grid, and remove squares at random, and then solve
it. Once solving it reaches a certain level of difficulty, then
there's your problem.
--
On-line canal route planner: http://www.canalplan.org.uk

(Waterways World site of the month, April 2001)
Jul 19 '05 #5


Nick Atty wrote:
On-line canal route planner: http://www.canalplan.org.uk


So the Travelling Salesman goes by narrow boat these days, does he?

Nigel

--
ScriptMaster language resources (Chinese/Modern & Classical
Greek/IPA/Persian/Russian/Turkish):
http://www.elgin.free-online.co.uk

Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
9997
by: Stewart Gordon | last post by:
I have a few Sudoku puzzles on my site. http://www.stewartsplace.org.uk/mindbenders/ But adding extra columns and rows to separate the 3x3 blocks seems a rather kludgy approach, and the result isn't aesthetically the best either. There ought to be a way of making the grids look nicer. I've played about a bit with rowgroups and colgroups before discovering that rowgroup is called tbody.
11
4147
by: ago | last post by:
Inspired by some recent readings on LinuxJournal and an ASPN recipe, I decided to revamp my old python hack... The new code is a combination of (2) reduction methods and brute force and it is quite faster than the ASPN program. If anyone is interested I attached the code in http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html
12
6348
by: kalinga1234 | last post by:
hy guys i am having a problem with my sudoku program which i coded using c++.; currently in my program if a duplicate number exist in either row/column/block i would make the particualr square 0. but thats not i want to do. I want to recurse back until until it find a correct number. i will post the function which i need the help; ---coding----------------------------------------------------------
0
6743
by: JosAH | last post by:
Greetings, a couple of years ago a large part of the world went totally mad. Not because of global climate changes, not because of terrible wars that were started in the Middle East, nor because of global famine, but because of a puzzle: Sudoku. This is what Sudoku is all about: +-------+-------+-------+
21
11380
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite some time and still not able to get the solution out. so i hope you guys can help me out. of course i am not expecting a full solution, but i would greatly appreciate it if anyone can suggest to me what should i do. i am very new to this subject so...
38
6400
by: Boon | last post by:
Hello group, I've been toying with a simple sudoku solver. I meant for the code to be short and easy to understand. I figured "brute force is simple" -- who needs finesse, when you've got muscle, right? :-) http://en.wikipedia.org/wiki/Sudoku Thus, the strategy is to test every legal "move" and to backtrack when stuck. A recursive function seemed appropriate. I'd like to hear
3
8607
by: deanchhsw | last post by:
Hello, I'm trying to build a program that solves sudokus and prints out the result on the screen. Here's the code for the class SudokuBoard. this will later be called in a class Sudoku. I'm a newbie, so making this took me hours and hours of time... // class SudokuBoard, will be called by class Sudoku import java.util.Scanner; import java.io.*; public class SudokuBoard { private int board = new int;
1
1872
by: deanchhsw | last post by:
Part A (http://bytes.com/topic/java/insights/645821-sudoku) B (http://bytes.com/topic/java/insights/739704-sudoku-b) C (http://bytes.com/topic/java/insights/739703-sudoku-c) this question refers to the Sudoku howto posted on this website. The links are shown above. My question centers around the boolean variables declared in Part A, such as the following. boolean rows= new boolean; ...
3
5976
by: DannyB13 | last post by:
Hi, and thanks for possible help in advance. Here's my dilemma. I've been making a sudoku generator, and I'm now stuck on one part. I must be able to take a 'solution' and verify that it is correct, by checking a few things. 1. There are enough numbers, no 'periods' which signify '0' or 'no input'. 2. That there are no duplicate numbers in any row, column, or 3x3 box. I have been thinking of ways to do this and I've come up with 2 things....
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10095
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9954
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8979
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.