SWI-序言-250
哦,男孩,我花了太长时间。
o(A,B,A+B).
o(A,B,A-B).
o(A,B,A*B).
t([],0).
t([A,B|T],D):-t(T,Q),o(A,B,C),o(C,Q,D).
t([A|T],C):-t(T,Q),o(A,Q,C).
a(A):-t(A,B),n(C),B>C,retract(n(C)),assert(n(B)).
m(A):-assert(n(0)),\+p(A),n(R),R2 is R,write(R2).
p(A):-permutation([0|A],B),a(B),0=1.
从命令行调用(例如):
> swipl -s filename.pl -g "m([1, 1, 1, 1, 1])" -t halt
6
(没有特别的原因,我发现我的高尔夫球功能名称拼写为“ tomato pot”,真是棒极了。)
非高尔夫版本:
% Possible operations
operation(Left, Right, Left + Right).
operation(Left, Right, Left - Right).
operation(Left, Right, Left * Right).
% Possible ways to transform
transform([], 0).
transform([A, B|T], D) :- transform(T, Q), operation(A, B, C), operation(C, Q, D).
transform([A|T], C) :- transform(T, Q), operation(A, Q, C).
% Throw the given array through every possible transformation and update the max
all_transforms(A) :- transform(A, B), n(C), B>C, retract(n(C)), assert(n(B)).
% Find all the permutations and transformations, then fail and continue execution.
prog(A) :- assert(n(0)), !, permutation([0|A], B), all_transforms(B), fail.
% End the program
finished :- n(R), write(R), nl, R2 is R, write(R2), nl.
% Run the program
main(A) :- ignore(prog(A)), finished.
说明:
- 接受数组作为参数。
- 获取数组的所有排列。
- 找到一些要添加到数组中的运算符。(这是通过动态编程完成的,看看是否可以将前两个元素组合在一起会更好。)
- 对照我们当前的最大值进行检查。如果更好,请更换它。
- 告诉程序我们失败了,以便它继续检查,但随后取反(使用
ignore
或\+
)以使谓词整体返回true
并继续。
- 我们给了一个谓词字符串,而不是一个数字字符串,因此请先使用它进行分配
is
,然后再编写它。