Skip to content

Instantly share code, notes, and snippets.

@ryloric
Created September 30, 2020 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryloric/df467a9b9b11f537e81f59c5bb0c3345 to your computer and use it in GitHub Desktop.
Save ryloric/df467a9b9b11f537e81f59c5bb0c3345 to your computer and use it in GitHub Desktop.
N-Queens in Lua and Fennel
(global N 12)
(fn place-ok? [a n c]
(var ok? true)
(var i 1)
(while (and ok? (< i n))
(set ok? (not (or (= (. a i) c)
(= (- (. a i) i) (- c n))
(= (+ (. a i) i) (+ c n)))))
(set i (+ 1 i)))
ok?)
(fn print-solution [a]
(for [i 1 N]
(for [j 1 N]
(io.write (if (= (. a i) j) "X" "-") " "))
(print))
(print))
(fn add-queen [a n]
(if (> n N)
(do
(print-solution a))
(for [c 1 N]
(when (place-ok? a n c)
(do
(tset a n c)
(add-queen a (+ 1 n)))))))
(add-queen [] 1)
-- Copied verbatim from Programming in Lua, 4th edition
-- board size
N = 12
-- check whether position (n,c) is free from attacks
function isplaceok(a, n, c)
for i = 1, n - 1 do
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
end
end
return true
end
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
io.write("\n")
end
-- add to board 'a' all queens from 'n' to 'N'
function addqueen(a, n)
if n > N then
printsolution(a)
else
for c = 1, N do
if isplaceok(a, n, c) then
a[n] = 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