-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinConflict.py
57 lines (40 loc) · 1.32 KB
/
MinConflict.py
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
import random
import time
count = 0
start_time = time.time()
def nqueens(nr):
show(min_conflicts(list(range(nr)), nr), nr)
def show(soln, nr):
for i in range(nr):
row = [' ~ '] * nr
for col in range(nr):
if soln[col] == nr - 1 - i:
row[col] = ' Q '
print(''.join(row))
end_time = time.time()
def min_conflicts(soln, nr, iters=1000):
def random_pos(li, filt):
return random.choice([i for i in range(nr) if filt(li[i])])
for k in range(iters):
confs = find_conflicts(soln, nr)
if sum(confs) == 0:
return soln
col = random_pos(confs, lambda elt: elt > 0)
vconfs = [hits(soln, nr, col, row) for row in range(nr)]
soln[col] = random_pos(vconfs, lambda elt: elt == min(vconfs))
def find_conflicts(soln, nr):
global count
count = count + 1
return [hits(soln, nr, col, soln[col]) for col in range(nr)]
def hits(soln, nr, col, row):
total = 0
for i in range(nr):
if i == col:
continue
if soln[i] == row or abs(i - col) == abs(soln[i] - row):
total += 1
return total
BOARD_SIZE = input('Please enter Board Size: ')
nqueens(BOARD_SIZE)
print("\nTime taken to complete: %s s" % (((end_time - start_time)) * 1))
print("No. of assignments: %s" % count)