lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi !

I am playing with the n-queen problem to learn Lua. I want to save all the solution in a list (solutions) but it does not work and I do not understand why. Here my very simple code with which my problem is more understandable.

Thanks for your help.

local N=6

local solutions={}

function NQueen(q,r)
   if r==N+1 then
      -- debug
      char=""
      for e=1,N do
         char=char..q[e].." "
      end
      print(char.."\n") -- THIS PRINT THE RIGHT ARRAYS
      -- end debug
      solutions[#solutions+1]=q
   else
      for j=1,N do
         valid=true
         for i=1,(r-1) do
            if ((q[i]==j or math.abs(q[i]-j)==math.abs(r-
i)) and r>1) then
               valid=false
            end
         end
         if valid then
            q[r]=j
            NQueen(q,r+1)
         end
      end
   end
end

Dq={}
for i=1,N do
  Dq[i]=0
end

NQueen(Dq,1)
print(#solutions.." solutions found") -- RIGHT NUMBER OF SOLUTIONS
local drawSol=solutions[2]
local char=""
for f=1,N do
   char=char..drawSol[f].." "
end
print(char) -- THIS PRINT A WRONG ARRAY



--
Maxime Chupin
http://mc.notezik.com