erlang 题目:一个integer列表,按照数字出现的次数由少到多排序,相同的数字小 的在前面...

比如 列表[1,1,1,1,2,2,2,4,4,4,4,4,4,3,3,5,6,6,6] 处理成
[5,3,3,2,2,2,6,6,6,1,1,1,1,4,4,4,4,4,4]


% -export([sort/1]).
-compile(export_all).
get_map(List) ->
lists:foldl(
fun(X, Map1) ->
% io:format("new map is ~p~n", [Map1]),
case maps:find(X, Map1) of
error ->
% io:format("before add map is ~p~n", [Map1]),
maps:put(X, 1, Map1);
{ok, Value} ->
% io:format("before update map is ~p~n", [Map1]),
maps:update(X, Value + 1, Map1)
end
end, #{}, List).

sort(List) ->
Map = get_map(List),
List1 = maps:to_list(Map),
List2 = lists:keysort(2, List1),
List4 = lists:foldl(
fun({Key, Value}, List3) ->
[lists:duplicate(Value, Key) | List3]
end, [], List2),
lists:flatten(lists:reverse(List4)).

test_sort() ->
List = [1,1,1,1,2,2,2,4,4,4,4,4,4,3,3,5,6,6,6],
sort(List).

 
 

测试:


1> c(sort_by_times).
{ok,sort_by_times}
2> sort_by_times:test_sort().
[5,3,3,2,2,2,6,6,6,1,1,1,1,4,4,4,4,4,4]
3> sort_by_times:get_map([1,1,3,3,3,3,2,2,2,2,2,6,6,6]).

{1 => 2,2 => 5,3 => 4,6 => 3}

4> Map =sort_by_times:get_map([1,1,3,3,3,3,2,2,2,2,2,6,6,6]).

{1 => 2,2 => 5,3 => 4,6 => 3}

5>

转载于:https://www.cnblogs.com/ShankYan/p/5411449.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值