-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_min.py
52 lines (36 loc) · 1.2 KB
/
example_min.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
#!/usr/bin/python
# A solution to N-Queens using the Min-Conflicts local search algorithm
# %%
import random
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))
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))
raise Exception("Incomplete solution: try more iterations.")
def find_conflicts(soln, nr):
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
nqueens(400)
# %%