Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Place Queens by yoichi
def place_queens(placed):
from itertools import combinations
for x, y in combinations(placed, 2):
if x[0] == y[0] or x[1] == y[1] or \
abs(ord(x[0]) - ord(y[0])) == abs(ord(x[1]) - ord(y[1])):
return set()
cols = list("abcdefgh")
rows = list("12345678")
for x in placed:
cols.remove(x[0])
rows.remove(x[1])
from itertools import permutations
for perm in permutations(rows, len(rows)):
add = [cols[i] + r for i, r in enumerate(perm)]
queens = placed.copy()
for a in add:
if all(abs(ord(q[0])-ord(a[0])) != abs(ord(q[1])-ord(a[1]))
for q in queens):
queens.add(a)
else:
break
else:
return queens
return set()
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
from itertools import combinations
COLS = "abcdefgh"
ROWS = "12345678"
THREATS = {c + r: set(
[c + ROWS[k] for k in range(8)] +
[COLS[k] + r for k in range(8)] +
[COLS[k] + ROWS[i - j + k] for k in range(8) if 0 <= i - j + k < 8] +
[COLS[k] + ROWS[- k + i + j] for k in range(8) if 0 <= - k + i + j < 8])
for i, r in enumerate(ROWS) for j, c in enumerate(COLS)}
def check_coordinate(coor):
c, r = coor
return c in COLS and r in ROWS
def checker(func, placed, is_possible):
user_set = func(placed.copy())
if not all(isinstance(c, str) and len(c) == 2 and check_coordinate(c) for c in user_set):
print("Wrong Coordinates")
return False
threats = []
for f, s in combinations(user_set.union(placed), 2):
if s in THREATS[f]:
threats.append([f, s])
if not is_possible:
if user_set:
print("Hm, how did you place them?")
return False
else:
return True
if not all(p in user_set for p in placed):
print("You forgot about placed queens.")
return False
if is_possible and threats:
print("I see some problems in this placement.")
return False
return True
assert checker(place_queens, {"b2", "c4", "d6", "e8"}, True), "1st Example"
assert checker(place_queens, {"b2", "c4", "d6", "e8", "a7", "g5"}, False), "2nd Example"
March 16, 2015