2013-04-08 1 views
0

나는 프롤로그에서 확률 적 검색을 구현하고 있습니다.프롤로그에서 n-queen을 확률 적으로 검색하는 방법은 무엇입니까?

코드는

queens_rand([],Qs,Qs) :- !. 
queens_rand(UnplacedQs,SafeQs,Qs) :- 
random_sort(UnplacedQs, UnplacedQs1), 
select(UnplacedQs,UnplacedQs1,Q), 
not_attack(SafeQs,Q,1), 
queens_rand(UnplacedQs1,[Q|SafeQs],Qs), 
!. 
queen_solve_rand(N) :- 
alloc(1,N,Ns), 
queens_rand(Ns,[], Q), 
write(Q), nl. 
random_sort([],_) :- !. 
random_sort(_,[]) :- !. 
random_sort(Xs, Ys) :- 
    length(Ys, L), 
    rnd_select(Xs,L, Ys), 
    write('Ys : '),write(Ys),nl. 

remove_at(X,[X|Xs],1,Xs). 
remove_at(X,[Y|Xs],K,[Y|Ys]) :- K > 1, 
K1 is K - 1, remove_at(X,Xs,K1,Ys). 

rnd_select(_,0,[]). 
rnd_select(Xs,N,[X|Zs]) :- N > 0, 
length(Xs,L), 
I is random(L) + 1, 
remove_at(X,Xs,I,Ys), 
N1 is N - 1, 
rnd_select(Ys,N1,Zs). 

not_attack([],_,_) :- !. 
not_attack([Y|Ys],X,N) :- 
X =\= Y+N, X =\= Y-N, 
N1 is N+1, 
not_attack(Ys,X,N1). 

select([X|Xs],Xs,X). 
select([Y|Ys],[Y|Zs],X) :- select(Ys,Zs,X). 

이지만 false를 반환합니다. 프롤로그를 잘 이해할 수는 없지만 구현해야합니다. 그리고 나는 틀린 곳을 찾을 수 없습니다.

답변

1

이 규칙을 제거해야합니다. random_sort (_, []) : -!. 첫 번째 arg가 무엇이든 그 결과는 []입니다.

+0

감사합니다. 하지만 그것은 무한 루프입니다. –

+0

다른 문제입니다. 코드를 추적해야합니다. – joel76