Created
July 7, 2019 15:45
-
-
Save mberlanda/6683968e0ec0d0e7977666e881d879d3 to your computer and use it in GitHub Desktop.
Eight Queens Puzzle in Lua
This file contains hidden or 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
N = 8 -- board size | |
function isplaceok(a, n, c) | |
for i = 1, n - 1 do -- for each queen already placed | |
if (a[i] == c) or -- same column? | |
(a[i] - i == c - n) or -- same diagonal? | |
(a[i] + i == c + n) then -- same diagonal? | |
return false -- place can be attacked | |
end | |
end | |
return true -- no attacks; place is OK | |
end | |
-- print a board | |
function printsolution(a) | |
for i = 1, N do --for each row | |
for j = 1, N do -- and for each column | |
-- writes "X" or "-" plus space | |
io.write(a[i] == j and "X" or "-"," ") | |
end | |
io.write("\n") | |
end | |
io.write("\n") | |
end | |
-- add to board 'a' all queens from 'n' to 'N' | |
function addqueen(a, n) | |
if n > N then -- all queens have been placed? | |
printsolution(a) | |
else -- try to place the n-th queen | |
for c = 1, N do | |
if isplaceok(a, n, c) then | |
a[n] = c -- place the n-th queen at column 'c' | |
addqueen(a, n+1) | |
end | |
end | |
end | |
end | |
-- run the program | |
addqueen({}, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment