【问题标题】:如何在Erlang中获取最频繁的元素
【发布时间】:2022-01-23 16:58:12
【问题描述】:

伙计们! 我需要编写一个函数,它会在列表中抛出我最常用的术语。 例如: uniq([a, [a,b], [a,b,c]]) -> a

如何使用 erlang 以递归方式完成?

【问题讨论】:

  • 你能澄清一下输入的类型吗?是List of List ([[]]) 还是List of either Atom or List of Atom ([ atom() | [atom()]])。 ?
  • @NalinRanjan [a | []]
  • 您能检查一下答案吗...让我们知道它是否适合您?

标签: functional-programming erlang erlang-otp erl


【解决方案1】:

这个怎么样....

-module(frequency).

-export([max_frequency/1]).

max_frequency(Values) ->
    CounterMap = build_counter_map(#{}, lists:flatten(Values)),
    key_with_max_value(maps:next(maps:iterator(CounterMap)), -1, none).
    
key_with_max_value (none, _, MaxVal) -> MaxVal;
key_with_max_value ({_Key, Value, Iterator}, CurrentMax, MaxVal) when CurrentMax > Value -> 
    key_with_max_value(maps:next(Iterator), CurrentMax, MaxVal);
key_with_max_value ({Key, Value, Iterator}, _CurrentMax, _MaxVal) ->
    key_with_max_value(maps:next(Iterator), Value, Key).

build_counter_map(CounterMap, []) -> CounterMap;
build_counter_map(CounterMap, [Key|RestOfValues]) ->
    Default = a_special_default_value,
    case maps:get(Key, CounterMap, Default) of
       Default ->
           build_counter_map(maps:put(Key, 1, CounterMap), RestOfValues);
       Value ->
           build_counter_map(maps:put(Key, (Value + 1), CounterMap), RestOfValues)
    end.

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多