erlang 如何找到最宽的山谷

7jmck4yq  于 2023-01-22  发布在  Erlang
关注(0)|答案(1)|浏览(146)

有代表块大小的数字列表,我想找出列表中最大的山谷形状。约束条件是,不像正常的山谷,两端可以像下面的例子[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有点递归,这就是为什么我需要一些帮助

ffscu2ro

ffscu2ro1#

我不是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).

相关问题