[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: n-queens -> save the solutions
- From: "Dimiter \"malkia\" Stanev" <malkia@...>
- Date: Mon, 01 Aug 2011 01:41:32 -0700
Hi Maxime,
You need to story a copy of your "q" array, because it gets modified later.
local N=6
local solutions={}
function NQueen(q,r)
if r==N+1 then
-- debug
char=""
local qcopy = {}
for e=1,N do
char=char..q[e].." "
qcopy[e] = q[e]
end
print(char.."\n") -- THIS PRINT THE RIGHT ARRAYS
-- end debug
solutions[#solutions+1]=qcopy
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
Thanks,
Dimiter "malkia" Stanev.
On 8/1/11 1:09 AM, Maxime Chupin wrote:
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