Search for maximum subscriptions in Prolog

I am new to Prolog and trying to resolve instances of the problem with maximum subaram .

I have the following pretty 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 am trying to get the maximum amount from f(L,M,N)where Lis the list, the Mresult (the maximum amount, as well as the maxsofar variable in C ++ code) I want to get Nis an intermediate variable like "maxendinghere" in C ++ code. I want to get the answer Lfrom his previous list L1, and the relation of variables is exactly 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 do not know where the problem is.

+4
1

Prolog :

< > : use_module (library (clpfd)).

zs_maxmum/2 :

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).

:

?- 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.

:

  • , .
  • , []. zs_maxmum([-2,-3,-4], 0) .
+3

Source: https://habr.com/ru/post/1569194/


All Articles