Created
November 15, 2016 13:08
-
-
Save weakish/68556f3cb04fa73b55a9b56b7058626a to your computer and use it in GitHub Desktop.
#eight-queen problem 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
--[[ | |
PiL Exercise 10.2: An alternative implementation for the eight-queen problem | |
would be to generate all possible permutations of 1 to 8 and, for each | |
permutation, to check whether it is valid. | |
--]] | |
local _ENV,M = require 'pl.import_into' () | |
local N = 8 | |
-- check whether position (n,c) is free from attacks | |
local 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 -- samn diagonal? | |
(a[i] + i == c + n) then -- same diagonal? | |
return false | |
end | |
end | |
return true -- no attacks, place is OK | |
end | |
-- print a board | |
local function printsolution(a) | |
for i = 1, N do | |
for j = 1, N do | |
io.write(a[i] == j and "X" or "-", " ") | |
end | |
io.write("\n") | |
end | |
end | |
for a in list(permute.table{1, 2, 3, 4, 5, 6, 7, 8}) do | |
for n,c in a do | |
if not isplaceok(a, n, c) then | |
break | |
end | |
printsolution(a) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment