let return x = [x]

let bind m f = List.flatten ( List.map f m )

let mzero = []

let mplus = List.append

let guard b = if b then return () else mzero

```
```let rec select = function

|[] -> mzero

|a::x -> mplus (return (a,x)) (bind (select x) ( fun (b,x') -> return

(b,a::x') ))

let notin q l = not(List.mem q l)

let range n =

let rec aux i l =

if i = 0 then l else i::(aux (i-1) l)

in List.rev ( aux n [] )

let rec place i rs d1 d2 = match i with

|0 -> return []

|i ->

bind (select rs) (fun (q,rs') -> (* select one queen *)

let q1 = q - i in

let q2 = q + i in

bind (guard (notin q1 d1)) (fun r1 ->

bind (guard (notin q2 d2)) (fun r2 ->

bind (place (i-1) rs' (q1::d1) (q2::d2)) (fun qs ->

(return (q::qs))))))

`let queen n = place n (range n) [] []`

Unfortunately, wordpress has destroyed your code by removing the white-space (and possibly mangling punctuation such as > and <). Even if it hadn’t, I believe the code is not similar to the original as it generates all solutions rather than back-tracking for a single solution so the benchmark would be invalid.

Ian

]]>“”” General solution to the 8 queens puzzle.

“””

class queen:

“”” A queen on a chess board.

“””

def __init__(self, row, col):

self.row, self.col = row, col

def __str__(self):

return “(%d, %d)” % (self.row, self.col)

def safe_from(self, queens):

“”” Is this queen safe from the list of queens?

“””

for queen in queens:

if self.attacked_by(queen):

return False

return True

def attacked_by(self, queen):

“”” Is this queen attacked by the input queen?

“””

r, c = self.row, self.col

qr, qc = queen.row, queen.col

def same_row():

return r == qr

def same_column():

return c == qc

def same_diagonal():

return r + c == qr + qc or r – c == qr – qc

return same_row() or same_column() or same_diagonal()

def queens_puzzle(board_size):

“”” Generate solutions to the Queens puzzle for the input board size.

“””

def queen_columns(cols):

if cols == 0:

yield list()

else:

cols -= 1

for queens in queen_columns(cols):

for row in range(board_size):

new_queen = queen(row, cols)

if new_queen.safe_from(queens):

yield queens + [new_queen]

for queens in queen_columns(board_size):

yield queens

def outer_join(s, seq):

return “%s%s%s” % (s, s.join(seq), s)

def print_solution(board_size, queens):

line = outer_join(“+”, “-” * board_size)

for row in range(board_size):

print line

print outer_join(“|”,

[" Q"[q.row == row] for q in queens])

print line

print

try:

print “””\

Queens puzzle solver.

Puts N chess queens on an N by N chessboard such that none of

them is able to capture any other.

At the prompt, enter the board size or Q to quit.

“””

while True:

board_size = int(raw_input(“board size (Q to quit)? “))

if board_size 16:

print (“That’s a tough one but I’ll try my best. ”

“Press CTRL-C to interrupt.”)

try:

solutions = 0

for solutions, queens in enumerate(queens_puzzle(board_size)):

print_solution(board_size, queens)

if solutions: solutions += 1 # Users count from 1, not 0

print “There %s %d solution%s to the %d Queen%s puzzle.\n” % (

solutions == 1 and “is” or “are”,

solutions, “s”[solutions==1:],

board_size,”s”[board_size==1:])

except KeyboardInterrupt:

print “Execution interrupted.”

except ValueError, v:

print “Bye for now!”

Try the above version too..

]]>