Don't know if anyone is interested in this, but since i just finished my quick and dirty brute force solution of the Queens Chess Problem using Python i thought that maybe i should publish it to see what kind of feedback i will get:
#!/usr/bin/python3'''Program to solve the "n x n chess board and n queens chess problem" fromMagPi 68 (magpi.cc/JgrHLH)Date: 13MAY2018Author: raymond gordon'''import sys, copy, pprint def is_solution(coordinates, dimensions): # check if multiple queens on same row for x in range(dimensions): pos = coordinates[x] for next_col in range(x + 1, dimensions): next_pos = coordinates[next_col] # check if multiple queens on same row if pos == next_pos: return None # check if multiple queens on same diagonal if (pos + next_col - x) == next_pos: return None if (pos - next_col + x) == next_pos: return None return coordinates def main(): solutions = [] dim = 0 while True: dim = input('Enter the size of the chess board: ') if dim.isdecimal(): break print('An intiger value is required. ', end='') dim = int(dim) if dim < 4: print('No solution exists for a board of dimension', dim, 'x', dim) print('Exiting program ...') return # populate this_permutation this_permutation = [] for n in range(dim): this_permutation.append(0) # calculate the number of permutations possible_permutations = dim for n in range(dim): possible_permutations *= dim # initialize the counter #placement_cnt = 0 # go through the permutations searching for all possible solutions for n in range(possible_permutations): rem = n for m in range(dim): this_permutation[m] = rem % dim rem //= dim # is this_permutation a solution? result = is_solution(copy.copy(this_permutation), dim) if result: # was this solution encountered previously? if result not in solutions: solutions.append(result) print('\nInvestigated', possible_permutations, 'possibilities.') sol_cnt = len(solutions) print(sol_cnt, 'solutions found.') print('\n==========\nSolutions:\n==========') print('\n("x" position is position of value in array.\n"y" position is value in array)\n') cnt = 0 for solution in solutions: cnt += 1 print() print('Solution', cnt, ':') pprint.pprint(solution) if __name__ == '__main__': main()
Unfortunately, the code is not being formatted properly here, so it is probably completely hopeless to understand.
- raymond