Created
November 7, 2013 18:18
-
-
Save zrbecker/7359337 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, time, random | |
def nQueens(n): | |
board = [i for i in xrange(n)] | |
optimal = 0 | |
current = n * (n - 1) / 2 | |
if n < 4: | |
return board | |
while current > optimal: | |
j = random.randint(0, n - 1) | |
attack = [0 for i in xrange(n)] | |
for i in xrange(n): | |
if i == j: continue | |
d1 = board[i] + j - i | |
d2 = board[i] + i - j | |
if 0 <= d1 and d1 < n: | |
attack[d1] += 1 | |
if 0 <= d2 and d2 < n: | |
attack[d2] += 1 | |
attack[board[i]] += 1 | |
small = n | |
moves = [] | |
for i in xrange(n): | |
if attack[i] < small: | |
moves = [] | |
small = attack[i] | |
if attack[i] == small: | |
moves.append(i) | |
current += small - attack[board[j]] | |
board[j] = random.choice(moves) | |
return board | |
if __name__ == '__main__': | |
n = int(sys.argv[1]) if len(sys.argv) >= 2 else 8 | |
verbose = False if len(sys.argv) >= 3 else True | |
start = time.time() | |
result = nQueens(n) | |
end = time.time() | |
if verbose: print result | |
print "Time: %.4f seconds" % (end - start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment