Question

i'm implement stochastic search in prolog.

code is

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).

but it returns false. i can't understand prolog well, but i have to implement it. and i cant find where is wrong.

Was it helpful?

Solution

Yyou should remove this rule : random_sort(_,[]) :- !.. It means that whatever is the first arg, the result is [].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top