我们有数字列表和运算符列表,我们必须通过定义找到等于状态的元素来运算元素
例如:
输入:
Numbers: 1,2,3
Operators: +,-,/,*,(,)
输出:
1-> +2+3 (not valid)
1-> +2-3 (not valid)
1-> -2+3 (valid)
.
.
2-> +3-1 (valid)
2-> +3+1 (not valid)
.
.
3-> +1+2 (valid)
3-> +1-2 (not valid)
并且仅显示有效状态...
此代码仅用于显示所有状态。我该如何发展他们以实现这一目标?
member_(In, X) :-
member(X, In).
get_calcul([N], _, Temp, Out) :-
append(Temp, [N], Out).
get_calcul([N|T], [Op|Top], Temp, Out) :-
append(Temp, [N, Op], Temp1),
get_calcul(T, Top, Temp1, Out).
all_operations(In, Out) :-
% if you have N numbers
length(In, Len),
% you need N-1 operators
LenOps is Len - 1,
length(LOps, LenOps),
setof(Op, LOps^Ops^
( maplist(member_([+,-]), LOps),
get_calcul(In, LOps, [], Ops),
atomic_list_concat(Ops, Op)
), Out).
查询:
all_operations([1,2,3], Out), maplist(writeln, Out).
答案 0 :(得分:1)
没有太多需要更改的地方:
member_(In, X) :-
member(X, In).
get_calcul([], [], Out, Out).
get_calcul([N|T], [Op|Top], Temp, Out) :-
append(Temp, [Op, N], Temp1),
get_calcul(T, Top, Temp1, Out).
all_operations(In, Out) :-
length(In, Len),
LenOps is Len - 1,
length(LOps, LenOps),
length(Input, LenOps),
setof([V,Op], LOps^Ops^Input^(maplist(member_([+,-,/,*]), LOps),
maplist(member_(In), Input),
get_calcul(Input, LOps, [], Ops),
atomic_list_concat(Ops, Op),
compute(Op, V),
member(V, In)), Out).
compute(Atom, V) :-
catch((term_to_atom(Term, Atom), V is Term), V, fail).
我们得到了:
?- all_operations([1,2,3], Out), maplist(writeln, Out).
[1,+1*1]
[1,+1/1]
[1,+2-1]
[1,+2/2]
[1,+3-2]
[1,+3/3]
[1,-1+2]
[1,-2+3]
[2,+1*2]
[2,+1+1]
[2,+2*1]
[2,+2/1]
[2,+3-1]
[2,-1+3]
[3,+1*3]
[3,+1+2]
[3,+2+1]
[3,+3*1]
[3,+3/1]
Out = [[1, '+1*1'], [1, '+1/1'], [1, '+2-1'], [1, '+2/2'], [1, '+3-2'], [1, '+3/3'], [1, '-1+2'], [1|...], [...|...]|...].