Erlang Applet: integer sequence, search for and for the positive longest-gen Sequence

Source: Internet
Author: User

I recently learned about Erlang and compiled a small program.


The algorithm is as follows:

Divide parameters into three

When the Pre-Sub-sequence (SAVE) of the current position (for example,-5,-1, _,...) is set to _, the pre-Sub-sequence is 1, 2,-1.

And the sum (cursum) (,-1) of this subsequence is 2)

The remaining number rest; the remaining number can also be expressed as [H | T], H is the first element, and T is the list element.


The process is as follows:

If the rest field is empty, the processing is complete. Print cursum and save.

If one element is left (rest only has one element)

If the sum of this element and cursum is still positive, this element should be included

Otherwise, do not include it.

Rest has multiple elements

If the sum of this element and cursum is still positive, the element should be included (saved to save, cursum updated to cursum + H), continue Recursion

Otherwise, because the addition of this element cursum is negative, there is no contribution to the subsequent sequence, because the re-calculation, before this, print save, make a break



-module(tut1).-export([maxlen_pos_sublist/3]).maxlen_pos_sublist(Save, CurSum, Rest) when Rest == [] ->  io:format("~p~n",[{sum, CurSum}, {list,Save}]);maxlen_pos_sublist(Save, CurSum, [H|T]) ->     case T == [] of        false ->            case CurSum+H > 0 of                 true-> maxlen_pos_sublist(Save++[H],CurSum+H,T);                false-> io:format("~p~n",[{sum, CurSum}, {list,Save}]), maxlen_pos_sublist([],0,T)            end;        true ->             case CurSum+H > 0 of                 true-> maxlen_pos_sublist(Save++[H],CurSum+H,[]);                false-> maxlen_pos_sublist(Save,CurSum,[])            end    end.% c(tut1).% tut1:maxlen_pos_sublist([],0,[1]).            % tut1:maxlen_pos_sublist([],0,[1,2]).            % tut1:maxlen_pos_sublist([],0,[1,3,-6,2,5]).



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.