Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created November 28, 2010 22:44
Show Gist options
  • Select an option

  • Save mattetti/719363 to your computer and use it in GitHub Desktop.

Select an option

Save mattetti/719363 to your computer and use it in GitHub Desktop.
Brute force height queens solution - http://en.wikipedia.org/wiki/Eight_queens_puzzle
n = 8
cols = (0..n-1).to_a
def board(vec)
vec.each do |col|
s = '-' * vec.size
s[col] = 'Q'
puts s
end
puts ''
end
cols.permutation(cols.size).each do |vec|
if (n == cols.map{|i| vec[i]+i}.uniq.size) && (n == cols.map{|i| vec[i]-i}.uniq.size)
board vec
end
end
from itertools import permutations
def board(vec):
for col in vec:
s = ['-'] * len(vec)
s[col] = 'Q'
print ''.join(s)
print
n = 8
cols = range(n)
for vec in permutations(cols):
if n == len(set(vec[i]+i for i in cols)) == len(set(vec[i]-i for i in cols)):
board(vec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment