Created
January 18, 2019 07:52
-
-
Save pulsejet/7ad56bf277aaeecb43d937692d06ff79 to your computer and use it in GitHub Desktop.
N-Queens : AMPL
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
# Solution to the n-queens problem in AMPL | |
# Author: Varun Patil <radialapps@gmail.com> | |
# I dedicate any and all copyright interest in this software to the | |
# public domain. I make this dedication for the benefit of the public at | |
# large and to the detriment of my heirs and successors. I intend this | |
# dedication to be an overt act of relinquishment in perpetuity of all | |
# present and future rights to this software under copyright law. | |
reset; | |
# MINOS cannot solve integer problems | |
options solver cplex; | |
# Size of board | |
param n := 8; | |
# Binary varible, so we can exclude the => 0 and <= 1 conditions | |
var s{1..n, 1..n} binary; | |
# Each row/column would have exactly 1 queen by logic | |
subject to horizontal{i in 1..n}: sum{j in 1..n} s[i,j] == 1; | |
subject to vertical{j in 1..n}: sum{i in 1..n} s[i,j] == 1; | |
# Prevent diagonal attack | |
subject to diagonal_one{k in 1..2*n-1}: sum{i in 1..n, j in 1..n : i+j == k} s[i,j] <=1; | |
subject to diagonal_two{k in -(n-1)..n-1}: sum{i in 1..n, j in 1..n : i-j == k} s[i,j] <=1; | |
# All set | |
solve; | |
# Cough up! | |
display s; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment