Created
December 13, 2015 08:58
-
-
Save tylerneylon/60fda91b0c177623be9b to your computer and use it in GitHub Desktop.
A Lua-based solution to the n-queens problem.
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
-- Call this function as `grid = can_find_solution(N)`. | |
function can_find_solution(N, x0, y0, grid) | |
x0, y0 = x0 or 0, y0 or 1 -- Set default vals (0, 1). | |
if grid == nil then | |
grid = {} | |
for i = 0, N do grid[i] = {} end | |
end | |
for x = 1, x0 - 1 do | |
if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then | |
return false | |
end | |
end | |
grid[x0][y0] = true | |
if x0 == N then return true end | |
for y0 = 1, N do | |
if can_find_solution(N, x0 + 1, y0, grid) then return grid end | |
end | |
grid[x0][y0] = nil | |
return false | |
end | |
-- Example usage: | |
local N = 8 | |
local grid = can_find_solution(N) | |
for y = 1, N do | |
for x = 1, N do | |
-- Print "|Q" if grid[x][y] is true; "|_" otherwise. | |
io.write(grid[x][y] and "|Q" or "|_") | |
end | |
print("|") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this script for fun. My goal was to illustrate that Lua can achieve a nice balance between readability and brevity.
The function that does all the work is 19 lines, and is relatively straightforward.
For reference, see the Rosetta Code page for the n-queens problem, which has code snippets from various languages solving this problem. As an example, the C++ solution has 102 lines. The JavaScript approach is better - only 32 lines - but I still think the Lua approach feels simpler and more readable. To give it credit, the first C solution on that page is solid.