有代表塊大小的數字串列,我想找出串列中最大的山谷形狀。約束是,不像正常的谷底,兩端可以像下面的例子一樣平坦 [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 有點遞回,這就是我需要幫助的原因
uj5u.com熱心網友回復:
我不是專家,但我會這樣解決問題:
-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).
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523502.html
標籤:递归二郎
