我一直在尝试在Prolog中编写一个无流量求解器。 Here is how the game looks like。 Prolog求解器应该找到它的解决方案。我已经开始做一些事情,但我肯定错过了一些部分而不确定下一步该怎么做。 这就是我现在所拥有的。由于这是一个家庭作业问题,我已经为我提供了一些部分,所以它们不需要任何改变。
:-include(entradaFlow9).
:-dynamic(varNumber/3).
symbolicOutput(0).
writeClauses:-
atleastOneColorPerNode,
atmostOneColorPerNode,
atmost1Connected,
atmost2Connected.
atleastOneColorPerNode:-
size(N),
between(1,N,I),
between(1,N,J),
between(1,N,K),
findall( x-I-J-K, between(1,N,J), C ),
writeClause(C),
fail.
atleastOneColorPerNode.
atmostOneColorPerNode:-
size(N),
between(1,N,I),
between(1,N,J),
between(1,N,K1),
between(1,N,K2),
K1<K2,
writeClause([ \+x-I-J-K1, \+x-I-J-K2 ] ), fail.
atmostOneColorPerNode.
atmost1Connected:-
c(I1,X1,Y1),
c(I2,X2,Y2),
I1 < I2,
size(N),
between(1,N,H),
distance((X1,Y1), (X2,Y2), X), X is 1, I2 is I1,
writeClause( [\+r-I1-H, \+r-I2-H] ), fail.
atmost1Connected.
atmost2Connected:-
c(I1,X1,Y1),
c(I2,X2,Y2),
c(I3,X3,Y3),
I1 < I2, I2 < I3,
size(N),
between(1,N,H),
distance((X1,Y1), (X2,Y2), X), X is 1,
distance((X1,Y1), (X3,Y3), Y), Y is 1,
I2 is I1, I3 is I2,
writeClause( [\+o-I1-H, \+o-I2-H, \+o-I3-H] ), fail.
atmost2Connected.
displayFlow(M).
% ========== No need to change the following: =====================================
main:- symbolicOutput(1), !, writeClauses, halt. % escribir bonito, no ejecutar
main:- assert(numClauses(0)), assert(numVars(0)),
tell(clauses), writeClauses, told,
tell(header), writeHeader, told,
unix('cat header clauses > infile.cnf'),
unix('picosat -v -o model infile.cnf'),
unix('cat model'),
see(model), readModel(M), seen, displaySol(M),
halt.
var2num(T,N):-
hash_term(T,Key),
varNumber(Key,T,N),!.
var2num(T,N):-
retract(numVars(N0)), N is N0+1,
assert(numVars(N)),
hash_term(T,Key),
assert(varNumber(Key,T,N)),
assert( num2var(N,T) ), !.
writeHeader:-
numVars(N),
numClauses(C),
write('p cnf '),write(N), write(' '),write(C),nl.
countClause:-
retract(numClauses(N)), N1 is N+1,
assert(numClauses(N1)),!.
writeClause([]):- symbolicOutput(1),!, nl.
writeClause([]):- countClause, write(0), nl.
writeClause([Lit|C]):- w(Lit), writeClause(C),!.
w( Lit ):- symbolicOutput(1), write(Lit), write(' '),!.
w(\+Var):- var2num(Var,N), write(-), write(N), write(' '),!.
w( Var):- var2num(Var,N), write(N), write(' '),!.
unix(Comando):-shell(Comando),!.
unix(_).
readModel(L):-
get_code(Char),
readWord(Char,W),
readModel(L1),
addIfPositiveInt(W,L1,L),!.
readModel([]).
addIfPositiveInt(W,L,[N|L]):-
W = [C|_], between(48,57,C),
number_codes(N,W), N>0, !.
addIfPositiveInt(_,L,L).
readWord(99,W):-
repeat,
get_code(Ch),
member(Ch,[-1,10]), !,
get_code(Ch1),
readWord(Ch1,W),!.
readWord(-1,_):-!, fail. %end of file
readWord(C,[]):- member(C,[10,32]), !. % newline or white space marks end of word
readWord(Char,[Char|W]):- get_code(Char1), readWord(Char1,W), !.
我的数据是:
size(9).
c(blue, 9,1, 2,2).
c(brown, 3,1, 8,4).
c(red, 3,4, 1,7).
c(cyan, 1,8, 4,4).
c(green, 1,9, 5,2).
c(yellow, 7,7, 7,9).
c(pink, 6,5, 8,7).
c(violet, 8,9, 9,6).
c(orange, 5,8, 8,8).