qubal
qubal

Reputation: 11

How to get most frequent element in Erlang?

I need to write a function, that would throw me most frequent term in list. Eg:

uniq([a, [a,b], [a,b,c]]) -> a

How can it be done recursive way using Erlang?

Upvotes: 1

Views: 118

Answers (1)

Nalin Ranjan
Nalin Ranjan

Reputation: 1782

How about this....

-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.

Upvotes: 1

Related Questions