0

I am trying to find how to find the number of solutions in a script. my current script is:

ksol(K,ST) :- length(L1,K), maketemplate(L1,ST,K), kset(Kset,K),
    asserta( (qn(K))),asserta( (st(ST))), asserta( (kset(Kset)) ).
                    % number of queens, solution template
maketemplate([],[],_K).
maketemplate([X|Rest],[N1/X|RT],K) :-  maketemplate(Rest,RT,K),
                                length([X|Rest],N),N1 is K-N+1,!.
kset([],0).
kset([N|Rest],N) :-N1 is N-1, kset(Rest,N1),!.

solution(L) :- st(L), sol(L).
sol([8]).   
sol([Q|Queens]) :- sol(Queens),      
         Q=_X/Y, kset(Kset),member(Y,Kset),
                  noattack(Q,Queens). 

more specifically, within this script, I am trying to see how many solutions are generated by prolog for 8 queens. would anyone be able to help me with this?

false
  • 10,264
  • 13
  • 101
  • 209
niconico
  • 9
  • 2

1 Answers1

1

Using assert/retract to count the number of successful goal calls is rather inefficient and error prone.

In SWI-Prolog, the easier solution is aggregate_all/3, available from the preloaded library(aggregate).

I'm not sure about which goal you want to count, assuming it's solution/1, you should use

?- aggregate_all(count,solution(_),N).

In Prolog dialects where library(aggregate) is not available, the easier way should be

?- findall(t,solution(_),L),length(L,N).
CapelliC
  • 59,646
  • 5
  • 47
  • 90