#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: penglaixy
#
# Created: 31/08/2013
# Copyright: (c) penglaixy 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import sys
#import string
import time
import random
import copy
def test(did_pass):
'''print the result of a test '''
linenum=sys._getframe(1).f_lineno
if did_pass:
msg = "Test at line{0} ok".format(linenum)
else:
msg = "Test at line{0} failed".format(linenum)
print msg
def share_diagonal(x0,y0,x1,y1):
dy = abs(y1-y0)
dx = abs(x1-x0)
return dy == dx
def col_clashed(bs, c):
for i in range(c):
if share_diagonal(i,bs[i],c,bs[c]):
return True
return False
def has_clashed(the_board):
length = len(the_board)
for i in range(1,length):
if col_clashed(the_board, i):
return True
return False
def test_suite():
rng = random.Random()
bd = list(range(8)) #modify the parameter to get board size of 4,8,16
num_found = 0
tries = 0
t0 = time.clock()
fruit_list = []
while num_found < 10:
rng.shuffle(bd)
tries += 1
if not has_clashed(bd):
if bd in fruit_list:
continue
fruit_list.append(copy.deepcopy(bd))
t1 = time.clock()
print ("Found solution {0} in {1:>4} tries time used: {2:.6f} seconds.".format(bd,tries,t1-t0))
tries = 0
num_found += 1
t0 = t1
print fruit_list
def main():
test_suite()
pass
if __name__ == '__main__':
main()
>>>
*** Remote Interpreter Reinitialized ***
>>>
Found solution [4, 6, 3, 0, 2, 7, 5, 1] in 273 tries time used: 0.003799 seconds.
Found solution [1, 5, 0, 6, 3, 7, 2, 4] in 405 tries time used: 0.005890 seconds.
Found solution [1, 6, 4, 7, 0, 3, 5, 2] in 91 tries time used: 0.001515 seconds.
Found solution [4, 6, 0, 3, 1, 7, 5, 2] in 896 tries time used: 0.013420 seconds.
Found solution [2, 4, 1, 7, 0, 6, 3, 5] in 1407 tries time used: 0.019014 seconds.
Found solution [6, 1, 5, 2, 0, 3, 7, 4] in 17 tries time used: 0.000559 seconds.
Found solution [1, 5, 7, 2, 0, 3, 6, 4] in 281 tries time used: 0.004027 seconds.
Found solution [3, 7, 0, 2, 5, 1, 6, 4] in 19 tries time used: 0.000532 seconds.
Found solution [0, 5, 7, 2, 6, 3, 1, 4] in 1962 tries time used: 0.026640 seconds.
Found solution [2, 4, 1, 7, 5, 3, 6, 0] in 250 tries time used: 0.003678 seconds.
[[4, 6, 3, 0, 2, 7, 5, 1], [1, 5, 0, 6, 3, 7, 2, 4], [1, 6, 4, 7, 0, 3, 5, 2], [4, 6, 0, 3, 1, 7, 5, 2], [2, 4, 1, 7, 0, 6, 3, 5], [6, 1, 5, 2, 0, 3, 7, 4], [1, 5, 7, 2, 0, 3, 6, 4], [3, 7, 0, 2, 5, 1, 6, 4], [0, 5, 7, 2, 6, 3, 1, 4], [2, 4, 1, 7, 5, 3, 6, 0]]
>>>