如何在Erlang中解决此问题?

o8x7eapl  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(191)

这里有一个数字列表,表示块的大小,我想找出列表中最大的谷形状。约束条件是,与正常谷不同,两端可以是平的,如下面的例子[5,5],仍然算作谷端
一些例子; [1, 5, 5, 2, 8] => [5, 5, 2, 8] widest valley [2, 6, 8, 5] => [2,6,8] widest valley [9, 8, 13, 13, 2, 2, 15, 17] => [13, 13, 2, 2, 15, 17] widest valley
这不是作业什么的,但我想知道我怎么能在Erlang解决它
我用另一种语言解出来的但是Erlang有点递归这就是为什么我需要一些帮助

rta7y2nd

rta7y2nd1#

我不是Maven,但我会这样解决这个问题:

-record(valley, {from=1, to=1, deepest=1}).

widest_valley([]) ->
    [];
widest_valley([H]) ->
    [H];
widest_valley([H,T]) ->
    [H,T];
widest_valley(L) ->
    widest_valley(L, #valley{}, #valley{}, 1, 2).

widest_valley(L, _Curr, Widest, _FlatFrom, Pos) when Pos > length(L) ->
    lists:sublist(L, Widest#valley.from, 1 + Widest#valley.to - Widest#valley.from);
widest_valley(L, Curr, Widest, FlatFrom, Pos) ->
    Before  = lists:nth(Pos - 1, L),
    AtPos   = lists:nth(Pos, L),
    Deepest = lists:nth(Curr#valley.deepest, L),
    Curr1 = if Before == Deepest ->
                    Curr#valley{deepest = if AtPos < Deepest ->
                                                  Pos;
                                             true            ->
                                                  Curr#valley.deepest
                                          end};
               AtPos < Before ->
                    #valley{from=FlatFrom, deepest=Pos};
               true ->
                    Curr
            end,
    FlatFrom1 = if AtPos == Before ->
                        FlatFrom;
                   true ->
                        Pos
                end,
    Widest1 = if Pos - Curr1#valley.from > Widest#valley.to - Widest#valley.from ->
                      Curr1#valley{to=Pos};
                 true ->
                      Widest
              end,
    widest_valley(L, Curr1, Widest1, FlatFrom1, Pos + 1).

相关问题