问题
I'm new to Prolog and trying to solve instances of the maximum subarray problem.
I have got the following quite elegant C++ code:
int maxSubArray(vector<int> List)
{
int maxsofar = 0;
int maxendinghere = 0;
for (int i = 0; i < List.size(); i++)
{
maxendinghere = max(maxendinghere+List[i], 0);
maxsofar = max(maxsofar, maxendinghere);
}
return maxsofar;
}
And here is my Prolog code:
max(X,X,X).
max(X,Y,X) :- X>Y.
max(X,Y,Y) :- X<Y. %define max function
prev(L,T,H) :-
reverse(L,[H|T1]),
reverse(T,T1). %split L to H(last element) and T(the remaining list)
f([],0,0).
f(L,M,N) :-
f(L1,M1,N1),
prev(L,L1,E),
max(M1,N,M),
max(K,0,N),
K is N1+E.
I try to get the maximum sum from f(L,M,N)
, where L
is the list, M
is the result (maximum sum, also like the variable "maxsofar" in C++ code) I want to get, N
is a intermediary variable as the "maxendinghere" in C++ code. I want to get answer of L
from its former list L1
, and the relation of variables are just the same as the C++ code.
However, the following query does not work:
?- f([1,2,3],X,Y).
is/2: Arguments are not sufficiently instantiated
I don't know where the problem is.
回答1:
This answer shows a Prolog port of kadanes-algorithm based on clpfd:
:- use_module(library(clpfd)).
We define zs_maxmum/2
like so:
zs_maxmum(Zs, MSF) :-
zs_maxmum_(Zs, 0,_, 0,MSF).
zs_maxmum_([], _,_, MSF,MSF).
zs_maxmum_([Z|Zs], MEH0,MEH, MSF0,MSF) :-
max(0,MEH0+Z) #= MEH1,
max(MSF0,MEH1) #= MSF1,
zs_maxmum_(Zs, MEH1,MEH, MSF1,MSF).
Sample queries:
?- zs_maxmum([-2,1,-3,4,-1,2,1,-5,4], Max).
Max = 6.
?- zs_maxmum([-2,3,4,-5,8,-12,100,-101,7], Max).
Max = 100.
A few remarks:
- We don't actually operate on arrays, but on lists.
- We admit arbitrary sublists, including
[]
. The goalzs_maxmum([-2,-3,-4], 0)
succeeds.
来源:https://stackoverflow.com/questions/27675467/finding-the-maximum-sublist-in-prolog