Skip to content

Instantly share code, notes, and snippets.

@weakish
Created November 15, 2016 13:08
Show Gist options
  • Save weakish/68556f3cb04fa73b55a9b56b7058626a to your computer and use it in GitHub Desktop.
Save weakish/68556f3cb04fa73b55a9b56b7058626a to your computer and use it in GitHub Desktop.
#eight-queen problem in #Lua
--[[
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